确定城市、州和邮政编码是否存在的最佳方法
我将数据存储到 NSMutableArray 中。
问题是 ABRecord 有时不完整。例如,我希望用户拥有以下数据,
First Name
Last Name
Street Address
City
State
Zip
Country
如果缺少城市、州、邮政编码,那么我会崩溃。那么有没有更好的检查方法呢?
这是我的代码,
- (NSString *)getCityStateAndZip
{
NSString* temp = [addressArray objectAtIndex:0];
if (temp != nil) {
NSArray *listItems = [temp componentsSeparatedByString:@","];
NSMutableArray* tempArray = [NSMutableArray arrayWithArray:listItems];
[tempArray removeObjectAtIndex:0];
if ([tempArray count] > 2) {
[tempArray removeObjectAtIndex:3];
}
temp = @"";
for (NSString* element in tempArray) {
if (element != nil) {
//NSLog(@"%@", element);
if ([element isEqualToString:@"(null)"]) {
NSLog(@"record has a null entry");
}
temp = [temp stringByAppendingString:element];
temp = [temp stringByAppendingString:@", "];
}
}
if ([temp length] > 1) {
temp = [temp substringToIndex:[temp length] -2];
}
}
return temp;
}
在我们开始删除元素之前,这是一个“po tempArray”。
(gdb) po tempArray
<__NSArrayM 0x5a6ee20>(
1 Main Street ,
Trenton ,
NJ ,
08601 ,
United States
)
谢谢
如果您有更好的方法来处理这个问题,我很想知道。
导致应用程序崩溃的行是
[tempArray removeObjectAtIndex:3];
我知道它崩溃的原因。如果缺少城市、州、邮政编码,并且数组小于 4,则无法删除该项目。
I store the data into an NSMutableArray
The issue is that the ABRecord is sometimes incomplete. For example, I am expecting the user to have the following data
First Name
Last Name
Street Address
City
State
Zip
Country
If City, State, Zip are missing then I crash. So is there a better way to check?
Here is my code
- (NSString *)getCityStateAndZip
{
NSString* temp = [addressArray objectAtIndex:0];
if (temp != nil) {
NSArray *listItems = [temp componentsSeparatedByString:@","];
NSMutableArray* tempArray = [NSMutableArray arrayWithArray:listItems];
[tempArray removeObjectAtIndex:0];
if ([tempArray count] > 2) {
[tempArray removeObjectAtIndex:3];
}
temp = @"";
for (NSString* element in tempArray) {
if (element != nil) {
//NSLog(@"%@", element);
if ([element isEqualToString:@"(null)"]) {
NSLog(@"record has a null entry");
}
temp = [temp stringByAppendingString:element];
temp = [temp stringByAppendingString:@", "];
}
}
if ([temp length] > 1) {
temp = [temp substringToIndex:[temp length] -2];
}
}
return temp;
}
Here is a 'po tempArray' before we start removing elements.
(gdb) po tempArray
<__NSArrayM 0x5a6ee20>(
1 Main Street ,
Trenton ,
NJ ,
08601 ,
United States
)
Thanks
If you have a better way of handling this, I'd love to know.
The line which crashes the app is
[tempArray removeObjectAtIndex:3];
I know why it crashes. If the city, state, zip are missing then it can't remove the item if the array is smaller than 4.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您寻找更好、更永久的解决方案时,除非我在您的代码中遗漏了某些内容,否则这至少不会阻止崩溃吗?
While you search for a better more permanent solution, and unless I am missing something in your code, wouldn't this at least stop the crash?