在我的应用中,用户可以创建无限的UITextField。然后我得到所有这些信息并上传到json文件中:
NSString *object;
NSString *object2;
NSString *object3;
NSString *object4;
NSString *object5;
NSString *size;
for (UITextField *text in array2) {
int touchedtag = text.tag;
NSUInteger tagCount = touchedtag;
switch (tagCount) {
case 1:
object = [NSString stringWithFormat:@"%@ %@ %@", text.text, NSStringFromCGRect(text.frame), text.font];
break;
case 2:
object2 = [NSString stringWithFormat:@"%@ %@ %@", text.text, NSStringFromCGRect(text.frame), text.font];
break;
case 3:
object3 = [NSString stringWithFormat:@"%@ %@ %@", text.text, NSStringFromCGRect(text.frame), text.font];
break;
case 4:
object4 = [NSString stringWithFormat:@"%@ %@ %@", text.text, NSStringFromCGRect(text.frame), text.font];
break;
case 5:
object5 = [NSString stringWithFormat:@"%@ %@ %@", text.text, NSStringFromCGRect(text.frame), text.font];
break;
default :
break;
}
}
NSArray *keys = [NSArray arrayWithObjects:@"text", @"text2", @"text3", @"text4", @"text5", nil];
NSArray *objects = [NSArray arrayWithObjects:object,object2,object3, object4, object5, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString* jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[jsonData writeToFile:path atomically:YES];
NSString *destDir = @"/sandbox/";
[[self restClient] uploadFile:filename toPath:destDir
withParentRev:nil fromPath:path];
[[self restClient] loadMetadata:@"/sandbox/"];
}
问题是对象的数量不是独立的(对象,对象2 ......)。因此,如果用户创建少于5个文本字段,则应用程序崩溃,而如果超过5个没有任何反应,则不会记录标记6及其中的信息。如何根据创建的字段数改变对象的数量?
答案 0 :(得分:0)
了解如何使用NSMutableArray:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
它允许您“动态”添加和删除对象,就像在许多其他语言中使用Vector
一样。 (Java,ActionScript,C ++ ......)
示例:强> (someValue是先前声明的变量)
stuff = [[NSMutableArray alloc] initWithCapacity: someValue];
[stuff insertObject:object1 atIndex:0];
[stuff insertObject:object2 atIndex:1];
[stuff insertObject:object2 atIndex:2];
...
此代码是使用特定数量的对象对其进行初始化,这些对象看起来就像您要找的那样。 NSMutableArray还允许您稍后调整数组中的对象数。