我正在尝试创建一个NSMutableArray字符。
lowerCaseLetters = [NSMutableArray new];
for (char crt = 'a'; crt <= 'z'; crt ++) {
NSString *chrStr = [NSString stringWithCString:&crt encoding:NSUTF8StringEncoding];
[lowerCaseLetters addObject:chrStr];
}
NSLog(@"%@",lowerCaseLetters);
结果:
"a@Ip",
"b@Ip",
"c@Ip",
"d@Ip",
"e@Ip",
"f@Ip",
"g@Ip",
"h@Ip",
"i@Ip",
"j@Ip",
"k@Ip",
"l@Ip",
"m@Ip",
"n@Ip",
"o@Ip",
"p@Ip",
"q@Ip",
"r@Ip",
"s@Ip",
"t@Ip",
"u@Ip",
"v@Ip",
"w@Ip",
"x@Ip",
"y@Ip",
"z@Ip"
)
为什么我会这样?有一个更好的方法吗? PS:有时这与“insertObject:atIndex:”崩溃无法插入nil对象....为什么?
答案 0 :(得分:2)
这是未定义的行为:
NSString *chrStr = [NSString stringWithCString:&crt encoding:NSUTF8StringEncoding];
问题是&crt
不是C字符串,因为C字符串必须以空值终止。你可以像这样解决它:
char buf[2];
buf[0] = crt;
buf[1] = '\0';
NSString *chrStr = [NSString stringWithCString:buf encoding:NSUTF8StringEncoding];
您还可以使用stringWithFormat:
来实现更简单的方法,例如:
NSString *chrStr = [NSString stringWithFormat:@"%c", crt];
答案 1 :(得分:1)
试试这个......
NSString *stringWithComma = @"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
NSArray *lowerCaseLetters = [[NSArray new] init];
lowerCaseLetters = [stringWithComma componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
NSLog(@"Array %@",lowerCaseLetters);
这会给你一个NSArray。如果需要NSMutableArray,则必须从NSArray中复制。
或简单地分配
NSMutableArray *lowerCaseLetters = [[NSMutableArray alloc] initWithObjects: @"a", @"b",...,@"z", nil];
第一种方法是动态的,因为您可以使用其中的任何值动态创建stringWithComma。
答案 2 :(得分:1)
继续使用dasblinkenlight,另一种方法是
for (unichar crt = 'a'; crt <= 'z'; crt ++) // note crt is now unichar
{
NSString *chrStr = [NSString stringWithCharacters: &crt length: 1];
[lowerCaseLetters addObject:chrStr];
}
继用户2734323后,另一种方法是
lowerCaseLetters = [@[ @"a", @"b", @"c", .... , @"x", @"y", @"z" ] mutableCopy];