开发者

Objective-C , array initialization

开发者 https://www.devze.com 2023-02-25 09:45 出处:网络
int num1, num2,num3,num4, i=0; NSMutableArray *charArray = [[NSMutableArray alloc] init]; while(num1 != 0 && num2 != 0) {
int num1, num2,num3,num4, i=0;
NSMutableArray *charArray = [[NSMutableArray alloc] init];

while(num1 != 0 && num2 != 0) {
  num3 = num1 & 1;
  num4 = num2 & 1;
  if(num3 != num4) {
    if(num3 == 0) {
      charArray[i++]= '0';
      charArray[i++]= '1';  
    } else {
      charArray[i++]='1';
      charArray[i++]='0';   开发者_运维技巧
    }
  }
  num1 = num1 > 1;
  num2 = num2 > 1;
}

}

I am kinda new to objective-c, can someone tell me whats wrong with this?


You can't use the regular array-like subscripts with NSArrays (and NSMutableArrays). To add an item, you need to call the addObject method.. i.e. [charArray addObject:obj].

The other caveat is you can't add a bare char to an NSArray, it needs to be Objective-C type. You can use the NSNumber class to wrap it. So your code would then be:

[charArray addObject:[NSNumber numberWithChar:'0']];
[charArray addObject:[NSNumber numberWithChar:'1']];

But you can still use a regular C array and leave your code unmodified, which is probably a better solution in your case. i.e.

char charArray[MAX_SIZE];


You can't access an NSMutableArray using the [] syntax of C.

You need to use the -[NSMutableArray addObject:] or -[NSMutableArray insertObject:atIndex:] methods.

0

精彩评论

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