开发者

Incrementing an NSNumber withInt by 1 inside of a block. Crashing on certain values

开发者 https://www.devze.com 2023-03-31 11:43 出处:网络
I am trying to create a generic \"BlockController\", where I set a block property to SOMEBLOCK. Then I can call that block on a BlockController update method, passing in properties from the BlockContr

I am trying to create a generic "BlockController", where I set a block property to SOMEBLOCK. Then I can call that block on a BlockController update method, passing in properties from the BlockController as parameters; ideally an NSArray of NSNumbers (with the idea that the block will pull the correct values from the indexes and set them accordingly).

I couldn't get the values to stay changed out of scope (I tried using __block, but must not have been doing that correctly). I've now changed the experiment to a simple incrementer using an "IntegerBlock", which is:

typedef int  (^IntegerBlock)();

I initialize my BlockController with

- (id)initWithIntegerBlock:(IntegerBlock)block defaultValue:(int)defaultValue {
self = [super init];
if (self) {
    _updateBlock = Block_copy(block);
    self.number = [NSNumber numberWithInt:defaultValue];
}

return self;

}

And here is the code I run:

- (void)viewDidLoad {
[super viewDidLoad];

IntegerBlock block = ^(NSNumber *n){
    int integer = [n intValue];
    integer++;
    n = [NSNumber numberWithInt:integer];
    return integer;
};

self.bc = [[BlockController alloc] initWithIntegerBlock:block defaultValue:0];
[self.bc update];

timer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(tick) userInfo:nil repeats:YES];
}

- (void)tick {
  [self.bc update];
}

I'm crashing when the number value hits 13.

I saw this post: NSNumber numberWithInt crashing on numbers >= 13

And my main looks like:

int main(int argc, char *argv[])
{
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   int retVal = UIA开发者_StackOverflow中文版pplicationMain(argc, argv, nil, nil);
   [pool release];
   return retVal;

}

Why is it crashing? Is there a more elegant way to do this? (I hope so)

0

精彩评论

暂无评论...
验证码 换一张
取 消