iOS - 将UILabel组存储到NSMutableArray中

时间:2011-07-18 17:04:27

标签: objective-c indexing nsmutablearray uilabel nsdictionary

我正在为每个循环动态创建UILabel。每个运行的循环都会创建1-4个UILabel。

我想要的是我将这些UILabel放入我的NSMutableArray中,以后能够轻松检索数据。

我最初的想法是将这些UILabel放入NSDictionary并使用[dictGroupLabels setValue:uiLabel1 forKey:@"uiLabel1"]然后使用[dictGroupLabels setValue:uiLabel2 forKey:@"uiLabel2"]等等。然后将这个字典放入我的NSMutableArray中,用于每个循环。稍后我可以访问UILabel *label = [[myArray objectAtIndex:0] valueForKey:@"uiLabel1"] 之类的值,但由于UILabel不符合NSCopying协议,因此遗憾地无效。

所以考虑到这一点你会如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

这个问题提供了有关您要完成的内容的更多信息。既然你知道在每种情况下你想要创建的可能的标签集,我强烈建议使用mutable dictionaries而不是数组。

为了说明,给出以下假设的类定义:

@interface MyClass: NSObject { 
    NSMutableDictionary * _labelDict; 
} 

@property (nonatomic, retain) NSMutableDictionary * labelDict; 

- ( void )methodA; 
- ( void )methodB; 
- (NSMutableDictionary *) labelsForRunLoop: (NSUInteger) loopIdx;
@end

您将拥有以下假设的类实现:

@implementation MyClass 

@synthesize labelDict = _labelDict; 

- ( id ) init { 
    if( ( self = [ super init ] ) ) { 
        [self setLabelDict: [NSMutableDictionary dictionaryWithCapacity: 8]]; 
    } 
} 

- ( void ) dealloc  { 
    [ self.labelDict release ]; 
    [ super dealloc ]; 
} 

- ( void ) methodA {
    for(NSUInteger i = 0; i < some index; i++) {
        [self.labelDict setObject: [self labelsForRunLoop: i] forKey: [NSString stringWithFormat: @"%d", i]];
    }
} 

- ( void ) methodB { 
    // Locate the label you need to work with. Example based on this crude pseudo code
    NSMutableDictionary * subDict = (NSMutableDictionary *) [self.labelDict objectForKey: @"0"];
    UILabel * theLabel = (UILabel * ) [subDict objectForKey: @"UILabel.Z"]; 
    theLabel.text = @"Label 1"; 
} 

- (NSMutableDictionary *) labelsForRunLoop: (NSUInteger) loopIdx {
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithCapacity: 4] ;
    [dictionary setObject: create-w-label forKey: @"UILabel.W"];
    [dictionary setObject: create-x-label forKey: @"UILabel.X"];
    [dictionary setObject: create-y-label forKey: @"UILabel.Y"];
    [dictionary setObject: create-z-label forKey: @"UILabel.Z"];

    return [dictionary retain];
}

@end

这基本上是伪代码,无法成功编译。然而,它将成为一个良好的起点。您可能希望将每个标签字典存储在一些有意义的键下,而不是仅使用循环索引。希望这会有所帮助。

答案 1 :(得分:1)

他们不需要遵守NSCopying就可以添加到数组中。听起来你只需要做这样的事情:

NSMutableArray *mainArray = [NSMutableArray array];

for(int i = 0; i < 5; i++)
{
    NSMutableArray *subArray = [[NSMutableArray alloc] initWithCapacity:5];

    for(int j = 0; j < 4; j++)
    {
        UILabel *label = [[UILabel alloc] init];
        // etc.
        [subArray addObject:label];
        [label release];
    }
    [mainArray addObject:subArray];
    [subArray release];
}

// then, to get one of the labels:

UILabel *someSpecificLabel = [[mainArray objectAtIndex:2] objectAtIndex:1];