无法访问Mutable数组

时间:2013-10-27 02:43:52

标签: ios objective-c arrays sorting object

我无法在数组中重新分配数据,而我正在尝试索引用户名。我能够将原始数组分成单个对象,但无法将值发送到我稍后需要引用的新数组。我self.userNamesArray = userNames;行中userNames的值和计数是正确的。但是在我记录self.userNamesArray之后,我得到(null)。任何提示都会导致我不能完全肯定我会欢呼!

·H

@property (nonatomic, copy) NSMutableArray *userNamesArray;

的.m

- (void)viewWillAppear:(BOOL)animated {

self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];

PFQuery *query = [self.friendsRelation query];
[query orderByAscending:@"username"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (error) {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
    else {
        self.friends = objects;

        NSArray *users = [self.friends valueForKey:@"username"];
        NSLog(@"username:%@", users);
        //Create an array of name wrappers and pass to the root view controller.
        NSMutableArray *userNames = [[NSMutableArray alloc] initWithCapacity:[self.friends count]];

        for (NSString *user in users) {

        componentsSeparatedByCharactersInSet:charSet];
            NSArray *nameComponents = [user componentsSeparatedByString:@" "];

            UserNameWrapper *userNameWrapper = [[UserNameWrapper alloc]    initWithUserName:nil nameComponents:nameComponents];

            [userNames addObject:userNameWrapper];
        }

        self.userNamesArray = userNames;

        NSLog(@"userNamesArray:%@",self.userNamesArray);

        [self.tableView reloadData];
    }

这是我需要引用self.userNamesArray的代码,在那里再次编译为nil。

- (void)setUserNamesArray:(NSMutableArray *)newDataArray {

if (newDataArray != self.userNamesArray) {
    self.userNamesArray = [newDataArray mutableCopy];
    if (self.userNamesArray == nil) {
        self.sectionsArray = nil;
        NSLog(@"user names empty");
    }
    else {
        [self configureSections];
    }
}

}

4 个答案:

答案 0 :(得分:1)

这段代码是递归调用的吗?

self.userNamesArray = [newDataArray mutableCopy];

等同于:

[self setUserNamesArray: [newDataArray mutableCopy]];

如果你需要覆盖赋值期间发生的事情,你可以像在这里一样做,但使用_userNamesArray来引用底层成员字段。

答案 1 :(得分:1)

将可变数组的属性方法更改为: -

    @property (nonatomic, retain) 
    NSMutableArray *userNamesArray;

答案 2 :(得分:0)

首先,我不需要NSMutableArray用于“userNamesArray”。你可以简单地使用NSArray。现在,尝试下面的代码,你应该很高兴:

self.userNamesArray = [NSMutableArray arrayWithArray:userNames];

答案 3 :(得分:0)

由于这一行,你可能会得到null:

NSArray *users = [self.friends valueForKey:@"username"];

将其更改为:

NSArray *users = [self.friends objectForKey:@"username"];

此外,请遵循@Abhinav的建议,以获得更清晰的代码:)