简体   繁体   中英

Updating contents of class variable NSMutableArray

I'm new to Objective C and iOS development in general, so if I missed some information that needs to be included please let me know and I'll do my best. At the same time, if any of my assumptions are incorrect or if I set this up totally dumb, please don't hesitate to yell at me. Thanks!

I have a class object called feeds . Here's how I initialize it in the .h file:

@interface ClassViewController : ContentViewController <UITableViewDelegate,
UITableViewDataSource> {
    NSMutableArray *feeds;
}
@property (nonatomic, strong) NSMutableArray* feeds;

and in the .m:

@dynamic feeds;

I'm trying to get results from JSON and load them up into the feeds . Let's assume that resArr has correct data in it:

NSArray *resArr = [results objectForKey:@"data"];

if([self->feeds count]) {
    [self->feeds removeAllObjects];
    [self->feeds addObjectsFromArray:resArr];
 }
 else {
     self->feeds = [[NSMutableArray alloc] initWithArray:resArr];
 }

Now, this works fine the first time (ie, the first time I put data into the array), but I get the following error subsequent times: *** -[NSMutableArray addObjectsFromArray:]: array argument is not an NSArray

I'm clueless. Any ideas?

Edit: JSON structures

1:

{"code":200,"data":[{"name":"ABM"},{"name":"ACC"}]}

2:

{"code":200,"data":{"100":{"subject":"ABM","title":"Decision Making in Agri-Food"},"130":{"subject":"ABM","title":"Farm Management I"}}}

you should use self.feeds instead of self->feeds, here's a good read Dot (“.”) operator and arrow (“->”) operator use in C vs. Objective-C

are you sure the subsequent times are actually NSArrays?

edit additon

Looks like the first JSon is just a array of names, where's as the second is a dictionary keyed with 100, 200, etc. So the JSON converts this into a dictionary keyed to 100, 200, ...

NSArray* resArr = [results objectForKey:@"data"];

if([self.feeds count]) {
    [self.feeds removeAllObjects];
    if([resArr isKindOfClass:[NSDictionary class]])
       [self.feeds addObjectsFromArray:resArr.allValues];
    else
       [self.feeds addObjectsFromArray:resArr];
 }
 else {
     self.feeds = [[NSMutableArray alloc] initWithArray:resArr];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM