开发者

NSMutable addObject problem

Noob here getting stuck and probably doing something stupid and would appreciate some guidance.

I've declared an NSMutableArray (resultArray) in my .h file, set the @property and @synthesize in the .m file.

In the initWithNibName i'm doing the alloc and init for the array:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
        resultArray = [[NSMutableArray alloc] init];
    }
    return self;
}

And in one of my methods i'm trying to do an addObject within a for loop, but whatever i try the array does not appear to contain objects (either by using objectAtIndex or count):

for (int i=[resultNumber length]; i>0; i--) {   
    NSString *theNumberRes = [NSString stringWithFormat:@"%c",[resultNumber characterAtIndex:i-1]]; 
    [resultArray addObject:theNumberRes];
}

NSLog(@"array count: %i", [resultArray count]);

I can step through the code and see the code running through the loop as man开发者_开发知识库y times as expected, but the NSLog never gives a result other than 0 (and hovering over the resultArray shows 0 objects at all times. (In brief, each object in the array is supposed to be a character from a string in reverse - e.g. if resultNumber is 12345, the array should store 5,4,3,2,1).

I have seen a number of other questions asking similar questions but they either don't seem to help or i don't understand the answer and didn't want to hijack someone else's question with my question.

Please could someone advise me as to how to get this working?


The question is if the - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil method get called. There is other initialization routines such as

-(id)init; 
-(id)initWithCoder:(NSCoder)aDecoder;

If your view is loading from a .xib file there is a possibility, that the last one is called and not the one you are initializing your array in.


The %c is what is messing you up. Look here

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

That is for 8-bit unsigned characters. If your string contains utf-8 characters, then this will not work. You could maybe use %C or you should use NSString initWithBytes:length:encoding

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜