[英]NSRange exception error to a nsmutablearray
我是iOS
新手。 我需要创建一个特定大小的数组并将其所有元素设置为0。比我需要在NSUserDefaults
添加此数组。
我做了以下事情:
//declare and initialize the array
NSString *name=@"test";
int y=5;
NSMutableArray *testArray = [[NSMutableArray alloc] initWithCapacity:100];
for (int i=0; i< [testArray count];i++) [testArray addObject:0]; //initialize all elements with 0
[[NSUserDefaults standardUserDefaults] setObject:testArray forKey:name];
//read the array form nsUserDefaults
NSMutableArray *testArray = [[[NSUserDefaults standardUserDefaults] objectForKey:name] mutableCopy];
[testArray replaceObjectAtIndex:y withObject:[NSNumber numberWithInt:1]]; //here i get the nsrangeexception index beyound bounds.
您的for条件是错误的,因为数组中没有对象,所以您的计数为0
for (int i=0; i< 100; i++)
应该是正确的
这应该为您工作:
//declare and initialize the array
NSString *name=@"test";
int y=5;
NSMutableArray *testArray = [[NSMutableArray alloc] init];
for (int i=0; i< 100;i++) [testArray addObject:@"0"];
[[NSUserDefaults standardUserDefaults] setObject:testArray forKey:name];
//read the array form nsUserDefaults
NSMutableArray *testArray1 = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:name]];
[testArray1 replaceObjectAtIndex:y withObject:@"1"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.