Alexander Alexander - 5 months ago 21
Objective-C Question

setText for Label - Objective C Xcode 7

I am very new to iOS development I have come across an issue where the label does not want to display the value in an NSArray. Please could someone help point out where it is wrong and why?

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

json_data = [json objectForKey:@"data"];

content = [json_data objectForKey:@"content"];

NSMutableArray *contentTemp = [[NSMutableArray alloc] initWithCapacity:content.count];

for (NSDictionary *contentInfo in content) {

project_details *mvm = [[project_details alloc] init];
mvm.bname = contentInfo[@"bname"];
mvm.burl = contentInfo[@"burl"];
mvm.p_num = contentInfo[@"p_id"];
mvm.pname = contentInfo[@"pname"];
mvm.pdesc = contentInfo[@"pdesc"];
mvm.purl = contentInfo[@"purl"];
mvm.plive = contentInfo[@"plive"];
mvm.pcompleted = contentInfo[@"pcompleted"];
mvm.days = contentInfo[@"days"];
mvm.pfunds = contentInfo[@"pfunds"];
mvm.amount = contentInfo[@"amount"];
mvm.perc = contentInfo[@"perc"];

[contentTemp addObject:mvm];

}

self.projectArray = contentTemp;

dispatch_async(dispatch_get_main_queue(), ^{
[self.label setText:[NSString stringWithFormat:@"%@", [self.projectArray valueForKey:@"bname"]]];

NSLog(@"%@", [self.projectArray valueForKey:@"bname"]);
});


}];

[dataTaskProject resume];


What I am getting when I run the code: NSLog prints the correct value but the setText method prints "(" to the label.

This is the code as is I did not put the URL in and there are no errors when running the code.

projectArray is defined in the .h file as: @property (nonatomic, copy) NSArray *projectArray;

This is what is printed in NSLog:

2016-06-06 18:28:10.281 #####[37127:1228517] (
"Global Giving" )

Answer

Calling valueForKey on an NSArray returns an NSArray. What you likely want instead is [(mvm *)self.projectArray.firstObject bname]. Your self.projectArray contains one or more mvm objects, and those are what have the bname property.

You can change .firstObject to an array index (i.e. [1], [2], etc.), depending what you want to access in the array (it's not clear to me from your code).

Comments