-4

在我的应用程序中,用户可以创建无限的 UITextFields。然后我得到所有这些信息并上传到一个 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/"];

}

问题是对象的数量不是独立的(object,object2 ...)。因此,如果用户创建的文本字段少于 5 个,则应用程序崩溃,而如果超过 5 个则没有任何反应,但标签 6 及以上的信息不会被记录。如何根据创建的字段数量改变对象数量?

4

1 回答 1

0

了解如何使用 NSMutableArray:https ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html

它允许您“即时”添加和删除对象,就像Vector在许多其他语言中使用 a 一样。(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 还允许您在以后调整数组中的对象数量。

于 2012-05-05T19:45:18.227 回答