Search code examples
objective-cnsarray

How to add elements in NSArray in Objective-C?


I want to add multiple elements in NSArray with @"title" and value.

for(int i = 0; i < size; i++){
    BSDevice *d=[[DeviceManager devices] objectAtIndex:i];
    self.dataArray =@[@{@"title":d.Name}];
}

But in this code it only adds one value. When I try with this method it doesn't work:

for(int i = 0; i < size; i++){
    BSDevice *d=[[DeviceManager devices] objectAtIndex:i];
    [self.dataArray addObject:@[@{@"title":d.buddyName}]];
}

I want to have multiple values with string and its value in NSArray like this @"title":d.Name,@"title":d.Name,@"title":d.Name


Solution

  • Your question isn't very clear and you didn't really explain what problem you are having with the second bit of code, but I think what you want is the following:

    for (BSDevice *d in [DeviceManager devices]) {
        [self.dataArray addObject:@{ @"title" : d.buddyName }];
    }
    

    This assumes that self.dataArray is an NSMutableArray and somewhere before this for loop you initialized self.dataArray as:

    self.dataArray = [NSMutableArray array];