小编Sal*_*rtz的帖子

在C#中生成代码的最佳方法类似于使用装饰器?

说我有一种我不断重复的模式.就像是:

static class C {
  [DllImport("mydll")]
  private static extern uint MyNativeCall1(Action a);
  public static uint MyWrapper1(Action a) {
    // Do something
    return MyNativeCall1(a);
  }

  [DllImport("mydll")]
  private static extern uint MyNativeCall2(Action a);
  public static uint MyWrapper2(Action a) {
    // Do something
    return MyNativeCall2(a);
  }

  //...

  [DllImport("mydll")]
  private static extern uint MyNativeCallN(Action a);
  public static uint MyWrapperN(Action a) {
    // Do something
    return MyNativeCallN(a);
  }
}
Run Code Online (Sandbox Code Playgroud)

所有这些中唯一不同的是本机函数和包装器方法的名称.有没有办法通过类似装饰器的东西生成它们?起初我认为C#属性是装饰器.也就是说,我可以通过类似的方式生成代码[GenerateScaffolding("MyNativeCall1")].但似乎属性更像是注释,实例化一个包含一些元数据的类.

C#也没有宏.有没有办法做到这一点?

要记住以下几点:

  • 我们的想法是包装器方法有额外的代码; 它们不仅仅是调用本机功能.
  • 这个想法也是生成的代码可以与类中的其他现有代码交错,而不是生成类文件本身; 类似装饰器或C/C++宏的东西.
  • 该方法不应该依赖于任何特定的IDE.具体来说,我不在Visual Studio上.

c#

16
推荐指数
3
解决办法
2086
查看次数

我应该如何在iOS中使用GCD dispatch_barrier_async(似乎在其他块之前而不是之后执行)

我正在尝试在iOS5中同步以下代码:

  1. 一个对象有一个方法,它发出一个HTTP请求,从中获取一些数据,包括一个图像的URL
  2. 一旦数据到达,文本数据将用于填充CoreData模型
  3. 同时,调度第二个线程异步下载图像; 当图像已经缓存并在CoreData模型中可用时,此线程将通过KVO发送信号到viewController.
  4. 由于图像下载需要一段时间,我们会立即将具有所有属性的CoreData对象返回给调用者.
  5. 此外,当第二个线程完成下载时,可以保存CoreData模型.

这是(简化)代码:

- (void)insideSomeMethod
{
    [SomeHTTPRequest withCompletionHandler:
     ^(id retrievedData) 
     {
         if(!retrievedData)
         {
             handler(nil);
         }

         // Populate CoreData model with retrieved Data...

         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
             NSURL* userImageURL = [NSURL URLWithString:[retrievedData valueForKey:@"imageURL"]];
             aCoreDataNSManagedObject.profileImage = [NSData dataWithContentsOfURL:userImageURL];
         });

         handler(aCoreDataNSManagedObject);
         [self shouldCommitChangesToModel];
     }];
}

- (void)shouldCommitChangesToModel
{
    dispatch_barrier_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSError *error = nil;
        if(![managedObjectContext save:&error]) 
        {
            //  Handle error
        }  
    });
}
Run Code Online (Sandbox Code Playgroud)

但是,正在发生的是基于屏障的保存块总是在图像加载块之前执行.那是,

dispatch_barrier_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            NSError *error = nil;
            if(![managedObjectContext save:&error]) 
            {
                //  Handle error
            } …
Run Code Online (Sandbox Code Playgroud)

concurrency cocoa-touch grand-central-dispatch ios objective-c-blocks

15
推荐指数
1
解决办法
2万
查看次数

如何将不同图层的核心动画链接到一个接一个?

我有一个启用了分页的scrollView和N个页面,它们是UIViews作为scrollView的子视图.

我正在尝试执行以下操作:

用户滚动到页码n.此时,之前添加到页码n的7个CALayers(即,页面[[scrollView子视图] objectAtIndex:n-1] .layer subLayers])逐个淡入.

但是我无法弄清楚如何使CALayers顺序淡入淡出.到目前为止,我已经从我的控制器的委托方法尝试了以下3种方法:(假设我有一个数组到层,并且他们的不透明度设置为0创建)

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
  int pageNumber = floor(self.scrollView.contentOffset.x / self.scrollView.frame.size.width);
  if(pageNumber == (n-1))
  {
    int timeOffset = 0;

    [CATransaction begin];
    for(CALayer *layer in layerArray)
    {
      CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"opacity"];
      a.duration = 6;
      a.beginTime = timeOffset++;
      a.fromValue = [NSNumber numberWithFloat:0.];
      a.toValue = [NSNumber numberWithFloat:1.];

      [layer addAnimation:a forKey:nil];
    }
    [CATransaction commit];
  }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
  int pageNumber = floor(self.scrollView.contentOffset.x / self.scrollView.frame.size.width);
  if(pageNumber == (n-1))
  {
    int timeOffset = 0;

    [CATransaction begin];
    for(CALayer …
Run Code Online (Sandbox Code Playgroud)

core-animation calayer ios

10
推荐指数
2
解决办法
5979
查看次数

如何在Blender导出脚本中导出每顶点UV坐标

我正在写一个来自Blender 2.64的python导出脚本.我的想法是我试图以OpenGL VBO友好的方式导出网格数据.所以我在结构布局数组中导出顶点属性.例如,对于具有顶点,法线和1对纹理坐标的网格,vertexAttributeVBO中的每个都将是8个连续的浮点数:

vvvnnntt 
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.问题是,当Blender进行UV映射时,它实际上可以将不同的uv分配给同一个顶点.

也就是说,假设你有一个立方体:你有8个顶点,你有6个面(在这种情况下为四边形).我原以为指数0,1,2,3的面/多边形意味着:

vertex 0, normal 0, uvCoord0 
vertex 1, normal 1, uvCoord1 
vertex 2, normal 2, uvCoord2 
vertex 3, normal 3, uvCoord3 
Run Code Online (Sandbox Code Playgroud)

因此,任何提及索引0,例如,在任何面上,总是意味着顶点0,正常0,uvCoord0元组.好吧,在Blender中,如果我理解正确,一个面可以用uvCoord 0引用顶点0,而另一个面可能用不同的uVCoord引用相同的顶点0.因此,一个face的loop_indices实际上必须用于在objets general data.verticesdata.uv_layers[].data容器中查找向量和uvCoord .

这允许每面应用uv贴图.所以你可以有一个立方体,其中每个面都应用了不同的uv纹理,即使两个相邻的面共享一个顶点,顶点也有不同的uv坐标,具体取决于面.

尽管如此,我的网格对于同一个顶点不应该有不同的uv,因为我正在展开相邻的面.这意味着在我的UV地图中,展开的网格是一组相邻的面(例如,如果它是由6个面构成的立方体,则为十字形),在两个相邻面之间,它们的公共顶点应该对应于相同的点在紫外线地图中.

所以鉴于上述情况,我认为这种方法应该有效:

vertexAttributeList = []
    for vertex in mesh.data.vertices:
        vertexAttribute = list(vertex.co)
        vertexAttribute.extend(list(vertex.normal))
        vertexAttributeList.append(vertexAttribute)

    for triangle in mesh.data.polygons:
        for uv_layer in mesh.data.uv_layers:
            for i in triangle.loop_indices:
                lookupIndex = mesh.data.loops[i].vertex_index
                if len(vertexAttributeList[lookupIndex]) == 6:
                    uvCoord = uv_layer.data[i].uv
                    vertexAttributeList[lookupIndex].extend([uvCoord[0], 1 - uvCoord[1]])
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,上面代码中的含义是我将不止一次访问顶点,因为我正在迭代共享顶点的网格面(本例中为三角形).每次我访问一个顶点时,如果它还没有分配它的UV坐标,那么我通过使用三角形的loop_indices查找它们来分配它们.毕竟,我的假设是,在一天结束时,每个顶点都有独特的uv coords.

上面的代码给出了以下布局,例如(我正在显示网格的前6个顶点属性): …

python blender blender-2.61

10
推荐指数
1
解决办法
6598
查看次数

音频单元中的等功率交叉淡入淡出?

这实际上更像是一个理论问题,但在这里:

我正在开发一种效果音频单元,它需要在干信号和湿信号之间进行相等的功率交叉渐变.

但我对于从线性衰减器到干流和湿流信号幅度的比例因子(增益)的映射函数的正确方法感到困惑.

基本上,我看到它用cos/sin函数或平方根完成...基本上近似对数曲线.但是,如果我们对幅度的感知是开始时的对数,那么这些将推子位置映射到幅度的曲线实际上不应该是指数的吗?

这就是我的意思:

假设:

  • signal[i] 表示信号中的第i个样本.
  • 每个样本是一个范围为[-1,1]的浮点数,幅度在[0,1]之间.
  • 我们的GUI控件是一个NSSlider,范围从[0,1],所以它原则上是线性的.
  • fader 是具有NSSlider值的变量.

第一次观察: 我们以对数方式感知振幅.因此,如果我们有一个线性推子,只是通过这样做来调整信号的幅度:signal[i] * fader我们所感知的内容(听觉,无论数学如何)都是这样的:

在此输入图像描述

这就是所谓的蹩脚的推子效应:我们从静音变为滑块中最左边一段的剧烈音量增加,经过中间音量似乎没有那么响亮.

因此,为了使推子"正确",我们要么以dB尺度表示,然后,就信号而言,做:signal[i] * 10^(fader/20)或者,如果我们要保持[0,1]或推子单位,我们可以做:signal[i] * (.001*10^(3*fader))

无论哪种方式,我们从NSSlider到我们将在代码中使用的推子变量的新映射现在看起来像这样:

在此输入图像描述

这是我们真正想要的,因为由于我们以对数方式感知振幅,我们基本上从线性(NSSLider范围0-1)映射到指数,并将这个指数输出馈送到我们的对数感知.事实证明:log(10^x)=x所以我们最终以线性(也就是正确的)方式感知幅度变化.

大.

现在,我的想法是两个信号之间的等功率交叉淡化(在这种情况下是干/湿水平NSSlider将输入混合到AU和来自它的处理输出)基本上只相同,只有一个滑块作用于两个假设信号都干[i]和湿[i].

因此,如果我的滑块范围从0到100并且干完全左,而湿是完全右,我最终会得到以下代码:

Float32 outputSample, wetSample, drySample = <assume proper initialization>
Float32 mixLevel = .01 * GetParameter(kParameterTypeMixLevel);
Float32 wetPowerLevel = .001 * pow(10, (mixLevel*3)); 
Float32 dryPowerLevel = .001 * pow(10, ((-3*mixLevel)+1));
outputSample = (wetSample * wetPowerLevel) + (drySample * dryPowerLevel);
Run Code Online (Sandbox Code Playgroud)

其图表将是:

在此输入图像描述

和以前一样,因为我们以对数方式感知振幅,这种指数映射实际上应该使我们听到交叉渐变是线性的.

但是,我已经看到使用近似值来记录交叉淡化的实现.意思是:

在此输入图像描述

但这些曲线实际上不会强调我们对振幅的对数感知吗?

audio macos core-audio audiounit

8
推荐指数
1
解决办法
2361
查看次数

ARC:如何在对象中注入自定义dealloc IMP,后者又调用原始dealloc而不会导致malloc错误

我正在尝试执行以下操作:

  1. 得到一个类'dealloc IMP
  2. 向所述类注入一个自定义IMP,它基本上称为原始dealloc IMP
  3. 当所述类的实例被释放时,两个IMP都应该运行.

这是我的尝试:

@implementation ClassB

- (void)dealloc
{
    NSLog(@"\n%@ | %@", self, NSStringFromSelector(_cmd));
}

@end


@implementation ClassC

- (void)swizzleMe:(id)target
{
    SEL originalDeallocSelector = NSSelectorFromString(@"dealloc");
    __block IMP callerDealloc = [target methodForSelector:originalDeallocSelector];
    const char *deallocMethodTypeEncoding = method_getTypeEncoding(class_getInstanceMethod([target class], originalDeallocSelector));
    IMP newCallerDealloc = imp_implementationWithBlock(^(id _caller) {
        NSLog(@"\n new dealloc | calling block %p for %@", callerDealloc, _caller);
        callerDealloc(_caller, originalDeallocSelector);
    });

    NSLog(@"\nswapping %p for %p", newCallerDealloc, callerDealloc);

    class_replaceMethod([target class],
                        originalDeallocSelector,
                        newCallerDealloc,
                        deallocMethodTypeEncoding);

}

@end
Run Code Online (Sandbox Code Playgroud)

要像这样使用:

ClassB *b = [[ClassB alloc] …
Run Code Online (Sandbox Code Playgroud)

cocoa cocoa-touch objective-c ios

8
推荐指数
2
解决办法
951
查看次数

UIKit Dynamics UICollisionBehavior碰撞没有反弹

我有一个视图,其边界设置为碰撞(setTranslatesReferenceBoundsIntoBoundaryWithInsets)和一个重力的子视图设置,以便它可以碰撞超视图边界.

我试图使碰撞0%有弹性,但我还没弄明白怎么样.我尝试了一个UIDynamicItemBehavior弹性为0的子视图,同样具有可笑的高摩擦力而且没有任何东西.我的理由是,0弹性已经意味着在力的作用下再次出现力量再生,但即使是负数似乎也没有做任何事情,也没有什么关系.

关于如何进行碰撞的任何想法都会吸收所有能量或任何使得子视图在碰撞边界时不反弹所需的能量?

uicollisionbehavior uidynamicbehavior uikit-dynamics

8
推荐指数
1
解决办法
4076
查看次数

C++ lambda:如果按值捕获,如何避免切片引用

我有一个方法,它接受一个参数,它是对基类的引用,并通过将方法实现包装在一个方法体的调用中排队 queue<function<void()>>

问题是我希望按值捕获方法的参数,以便队列中的每个lambda可以使用自己的副本执行.

但是如果我按值捕获,那么引用参数的lambda副本似乎会对它进行切片,而是留下基类副本而不是引用中的实际派生类.

如果我通过引用捕获参数,我确实得到了lambda中的实际派生类,但是obj可能超出了方法调用之间的范围,或者它的状态可以改变.

请注意,该方法应该是可重入的,但不是异步的,也不是并发的.

这是我的意思(省略队列)的一个例子:

struct BaseObj {
    virtual ~BaseObj() = default;
};

struct DerivedObj : public BaseObj {

};

void someMethod(BaseObj& obj) {

    //  obj is of type BaseObj:
    std::cout << "\nobj type:" << typeid(obj).name();

    auto refLambda = [&] {
        //  captured obj is of type DerivedObj:
        std::cout << "\nrefLambda::obj type:" << typeid(obj).name();
    };

    auto valLambda = [=] {
        //  captured obj is of type BaseObj:
        //  presumably because it was copied by value, which sliced it. …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11 c++14

7
推荐指数
1
解决办法
473
查看次数

在模拟器中从5切换到4.3时,iOS应用程序完全未对齐

我正在开发一个理想的目标应用程序,一直到iOS 3.2.不过,我正在Lion上开发它并使用最新的5 sdk.据我所知,我没有使用任何sdk 5特定功能.但:

在iOS 5或模拟器(设置为v.5)的任何设备上,该应用程序工作得很好.在iOS 4.3或更低版本的任何设备上(设置为v.4.3的模拟器都是如此),与视图帧有关的一些内容会出现错位.

例如,这里有两个例子:

警报视图中的活动指示器.这是代码:

NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:fileRequest delegate:self];
  if(urlConnection) 
  {
    uistatusDialog = [[UIAlertView alloc] initWithTitle:(description ? NSLocalizedString(description, nil) : NSLocalizedString(@"Downloading", nil))
                                                message:nil
                                               delegate:nil 
                                      cancelButtonTitle:nil
                                      otherButtonTitles:nil];

    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicator.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin  | 
                                  UIViewAutoresizingFlexibleRightMargin | 
                                  UIViewAutoresizingFlexibleTopMargin   | 
                                  UIViewAutoresizingFlexibleBottomMargin);

    [indicator startAnimating];
    [uistatusDialog addSubview: indicator];
    [uistatusDialog show];
    [indicator release];
Run Code Online (Sandbox Code Playgroud)

以下是两个模拟器的截图:iOS 5:正确 iOS 5:正确 iOS 4.3:未对齐 iOS 4.3:未对齐

我通过[UILabel alloc] initWithFrame:CGRectMake(...]设置帧的标签也发生了类似的事情.

这段代码,例如:

UITableViewCell * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                   reuseIdentifier:reuseIndentifier] autorelease];

  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  cell.selectionStyle = UITableViewCellSelectionStyleGray; …
Run Code Online (Sandbox Code Playgroud)

cocoa-touch uiview ios4 ios ios5

5
推荐指数
1
解决办法
852
查看次数

如何使用核心数据Integer 64属性?

我希望Core Data中的Entity属性是64位整数.由于该模型将在iOS上运行,并且据我所知这些设备不是64位,我认为这NSNumber是要走的路(核心数据为您提供了对象的选项或基本类型的标量属性).我假设NSNumber将在内部负责跟踪64位的合适表示.

现在,我需要在某个时刻从我的实体中的这个"64位"属性中减去1(如果您没有猜到,64位属性是Twitter API中的max_id参数),但为此,我首先需要取消打包NSNumber属性中的数字.

我应该得到intValue吗?的longValue?unsignedIntValue?unsignedLongValue?好久不见?哪一个?

cocoa-touch properties core-data nsnumber ios

5
推荐指数
1
解决办法
5303
查看次数