How to add one NSArray data to another NSArray fields? - ios

I tought question title is little bit mismatch , can you please see the following explanation...
Currently i am having 2 NSArray's of data:
NSArray *arr1 = [[NSArray alloc]initWithObjects:#"aa",#"bb",#"1",#"cc", nil];
NSArray *arr2 = #[self.lbl1, self.lbl2, self.lbl3, self.lbl4];
In 1st Array i got data from server
I need to load those parameters in specific UILabel's in 2nd Array
I am looking O/P is::
self.lbl1.text = #"aa";
self.lbl2.text = #"bb";
self.lbl3.text = #"1";
self.lbl4.text = #"cc";
Is there any possiblity, can you please help me out..
in ViewController.h
#property (strong, nonatomic)IBOutlet UILabel* lbl1;
#property (strong, nonatomic)IBOutlet UILabel* lbl2;
#property (strong, nonatomic)IBOutlet UILabel* lbl3;
#property (strong, nonatomic)IBOutlet UILabel* lbl4;
in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *arr1 = [[NSArray alloc]initWithObjects:#"aa",#"bb",#"1",#"cc", nil];
NSArray *arr2 = #[self.lbl1, self.lbl2, self.lbl3, self.lbl4];
for(int i=0;(i<[arr1 count])&&(i<[arr2 count]);i++)
{
UILabel *label = (UILabel*)[arr2 objectAtIndex:i];
label.text = (NSString*)[arr1 objectAtIndex:i];
}
NSLog(#"%#,\n %#,\n %#, \n%#",self.lbl1,self.lbl2,self.lbl3,self.lbl4);
}
CRASH like:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:

Store the labels in the arrays, not their text property.
NSArray *arr1 = [[NSArray alloc]initWithObjects:#"aa",#"bb",#"1",#"cc", nil];
NSArray *arr2 = #[self.lbl1, self.lbl2, self.lbl3, self.lbl4];
for(int i=0;(i<[arr1 count])&&(i<[arr2 count]);i++)
{
UILabel *label = (UILabel*)[arr2 objectAtIndex:i];
label.text = (NSString*)[arr1 objectAtIndex:i];
}
Checking for count of both like : (i<[arr1 count])&&(i<[arr2 count]) ensures that the app does not crash if somehow the arrays become of different count.

Short answer: It is Not possible the way you want to do it.
This is because self.lbl1.text is a NSString and not attached to self.lbl1 anymore (text is a copy property of UILabel). If you change this NSString, you
would not change the value of self.lbl1.text
A better approach may be to save only the label, not its value:
NSArray *arr2 = #[self.lbl1, self.lbl2, self.lbl3, self.lbl4];
In this case, you could loop through your array:
for (NSInteger i=0; i < arr2.count && i < arr1.count; i++) {
((UILabel*)[arr2 objectAtIndex:i]).text = [arr1 objectAtIndex:i];
}

You can't directly do that but you can set arr2 to:
arr2 = #[self.lbl1, self.lbl2, self.lbl3, self.lbl4];
and then
for (UILabel *lbl in arr2) {
NSInteger i=[arr2 indexOfObject:lbl];
lbl.text = [arr1 objectAtIndex:i];
}

Assuming both arrays have the same size, you can do:
NSArray *arr3 = #[self.lbl1, self.lbl2, self.lbl3, self.lbl4];
for (NSUInteger i = 0; i < arr1.count; i++) {
arr3[i].text = arr1[i];
}
If the size of the array received from the server may vary, you can use MIN(arr1.count, arr3.count), i.e. minimum of the two sizes, so you won't get an out-of-bounds exception:
for (NSUInteger i = 0; i < MIN(arr1.count, arr3.count); i++) {
arr3[i].text = arr1[i];
}

Related

Array set to nil after an iteration

I have a problem where an attribute turns to nil after an iteration:
NSMutableArray * lojas = [[NSMutableArray alloc] init];
for (int x = 0; x < lojaResultado.count; x++) {
NSDictionary * listaAtributos = [lojaResultado objectAtIndex: x];
Loja * loja = [[Loja alloc] init];
NSMutableArray * produtosLista = [[NSMutableArray alloc] init];
[loja setName: [listAtributos objectForKey: #"Loja"]];
NSArray * produtosResultado = [[NSArray alloc] initWithArray: [listaAtributos objectForKey: #"Produtos"]];
for(int y = 0; y < produtosResultado.count; y++){
NSDictionary * produtoAtributos = [produtosResultado objectAtIndex:y];
Produto * produto = [[Produto alloc] init];
[produto setNome: [produtoAtributos objectForKey:#"Nome"]];
getNumber = [produtoAtributos objectForKey: #"Tipo"];
[produto setTipo: [getNumber intValue]];
getNumber = [produtoAtributos objectForKey: #"Tamanho"];
[produto setTamanho: [getNumber intValue]];
[produtosLista addObject: produto];
}
loja.produtos = produtosLista;
[lojas addObject: loja];
}
During the iteration I can see, at the debug mode, that my objetc loja receive the correct name on the method setName and the correct list (loja.produtos = produtosLista).
After add the object loja into my array lojas I can see the correct object, but when the second iteration starts, the object at the first array position has its attribute produtos (array) setted to nil.
Has someone had this problem before? Or can someone say what I am doing wrong?
Loja .h file:
#property (nonatomic) NSString * name;
#property (strong, nonatomic) NSMutableArray * produtos;
I saw in your code that [produtosLista addObject: tires]; but tires is not created in the method block, its seems like in second iteration tires is flushed out.
as your implementation its seems like you want to add product, can you try this code.
Update:
I updated the code snippet with using fast enumeration and removed alloc/init for array allocation and used autorelease concept.
NSMutableArray * lojas = [[NSMutableArray alloc] init];
for (NSDictionary *listaAtributos in lojaResultado) {
Loja * loja = [[Loja alloc] init];
[loja setName:[listAtributos objectForKey: #"Loja"]];
NSMutableArray * produtosLista = [NSMutableArray array];
for(NSDictionary * produtoAtributos in [listaAtributos objectForKey: #"Produtos"]){
Produto * produto = [[Produto alloc] init];
[produto setNome:[produtoAtributos objectForKey:#"Nome"]];
[produto setTipo:[[produtoAtributos objectForKey: #"Tipo"] intValue]];
[produto setTamanho:[[produtoAtributos objectForKey:#"Tamanho"] intValue]];
[produtosLista addObject:produto];
}
[loja setProdutos:produtosLista];
[lojas addObject: loja];
}

NSInternalInconsistencyException for NSMutableArray

I'm trying to add objects to an NSMutableArray but it keeps giving me this error.:
NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
I have researched this problem, and I'm not doing anything wrong that past people have done, so I have no idea what's wrong. Here is my code:
Group.h
#property (strong, nonatomic) NSString *custom_desc;
#property (strong, nonatomic) NSMutableArray *attributes; //I define the array as mutable
Group.m
#import "Group.h"
#implementation Group
-(id)init
{
self = [super init];
if(self)
{
//do your object initialization here
self.attributes = [NSMutableArray array]; //I initialize the array to be a NSMutableArray
}
return self;
}
#end
GroupBuilder.m
#import "GroupBuilder.h"
#import "Group.h"
#implementation GroupBuilder
+ (NSArray *)groupsFromJSON:(NSData *)objectNotation error:(NSError **)error
{
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil) {
*error = localError;
return nil;
}
NSMutableArray *groups = [[NSMutableArray alloc] init];
NSDictionary *results = [parsedObject objectForKey:#"result"];
NSArray *items = results[#"items" ];
for (NSDictionary *groupDic in items) {
Group *group = [[Group alloc] init];
for (NSString *key in groupDic) {
if ([group respondsToSelector:NSSelectorFromString(key)]) {
[group setValue:[groupDic valueForKey:key] forKey:key];
}
}
[groups addObject:group];
}
for(NSInteger i = 0; i < items.count; i++) {
//NSLog(#"%#", [[items objectAtIndex:i] objectForKey:#"attributes"]);
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:#"attributes"]; //this returns a NSArray object understandable
Group *g = [groups objectAtIndex:i];
[g.attributes addObjectsFromArray:[att mutableCopy]]; //I use mutable copy here so that i'm adding objects from a NSMutableArray and not an NSArray
}
return groups;
}
#end
Use options:NSJSONReadingMutableContainers on your NSJSONSerialization call.
Then all the dictionaries and arrays it creates will be mutable.
According to the error message you are trying to insert an object into an instance of NSArray, not NSMutableArray.
I think it is here:
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:#"attrib`enter code here`utes"]; //this returns a NSArray object understandable
Items is fetched from JSON and therefore not mutable. You can configure JSONSerialization in a way that it creates mutable objects, but how exactly I don't know out of the top of my head. Check the references on how to do that or make a mutable copy:
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:#"attributes"] mutableCopy];
Next try, considering your replies to the first attempt:
#import "Group.h"
#implementation Group
-(NSMutableArray*)attributes
{
return [[super attributes] mutableCopy];
}
#end

How to initialize a dictionary from NSString to NSArray

I am trying to create a dictionary (Not sure whether it should be NSDictionary or NSMutableDictionary) from NSString to an array (Not sure whether it should be NSArray or NSMutableArray).
property:
#property(nonatomic, readonly) NSMutableDictionary * categories;
implementation:
#synthesize categories = _categories;
- (NSMutableDictionary *)categories{
if(! _categories) {
for(PFObject * each in self.products) {
NSString * currentcategory = [each valueForKey:#"subtitle"];
NSArray * currentlist = [_categories objectForKey:currentcategory];
if(! currentlist) {
currentlist = [[NSArray alloc] init];
}
NSMutableArray * newArray = [currentlist mutableCopy];
[newArray addObject:each];
NSArray * newlist = [NSArray arrayWithArray:newArray];
[_categories setObject:newlist forKey:currentcategory];
}
}
NSLog(#"After constructor the value of the dictionary is %d", [_categories count]);
return _categories;
}
From the debug NSLog I realize that the dictionary is empty after the construction. What is wrong here and how shall I change it?
After code line
if(! _categories) {
add
_categories = [NSMutableDictionary new];
If you did not initialize _category array somewhere in code then.
you must instantiate it inside
if(!_categories)
Your NSMutableArray _categories instance is not allocated and initialized yet.
To create instance of NSMutableArray just add
_categories = [NSMutableArray arrayWithCapacity:0];

Add object to NSMutableArray in another class

Hi I have a grouped tableview the first section contains a list of emails and the second section just has two rows which are add email manually and select email from contacts.
The log in ManualEmail.m keeps logging 0 for the count and the array in EmailViewController is never modified, but I can't figure out what's wrong
This is my current set up
EmailViewController.h
#property (nonatomic, retain) IBOutlet NSMutableArray *dataArray;
EmailViewController.m
#synthesize dataArray;
- (void)viewDidLoad {
[super viewDidLoad];
dataArray = [[NSMutableArray alloc] init];
NSMutableArray *listItems = [[NSMutableArray alloc] initWithObjects:nil];
[listItems addObject:[ObjectArrays productWithType:#"test" Eemail:#"test#website.com" Eselected:YES]];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:listItems forKey:#"data"];
[dataArray addObject:firstItemsArrayDict];
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:#"Add Email Address From Contacts", #"Add Email Address Manually", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:#"data"];
[dataArray addObject:secondItemsArrayDict];
[tableView reloadData];
}
ManualEmail.m
EmailViewController *emailPVC = [[EmailViewController alloc] init];
NSDictionary *dictionary = [emailPVC.dataArray objectAtIndex:0];
NSArray *array = [dictionary objectForKey:#"data"];
NSMutableArray *emailArray = [NSMutableArray arrayWithArray:array];
[emailArray addObject:[ObjectArrays productWithType:name.text Eemail:email.text Eselected:YES]];
[emailPVC.dataArray removeObjectAtIndex:0];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:emailArray forKey:#"data"];
[emailPVC.dataArray insertObject:firstItemsArrayDict atIndex:0];
NSLog(#"%d", [emailPVC.dataArray count]);
In ManualEmail.m, you're creating the EmailViewController in code. But you aren't ever calling anything that would call its -viewDidLoad method, so the dataArray isn't ever getting created or filled out. You need to call emailPVC.view = <some view you created>; in order for -viewDidLoad to get called.

how to retrieve a NSArray from a custom class

I have a custom class which has a integer as a variable.
// addons.h
-(NSMutableArray *) goodDirections:(int)iNumber;
// addons.m
-(NSMutableArray *) goodDirections:(int)iNumber;
{
NSString *gOne = #"one"+iNumber;
NSString *gTwo = #"two"+iNumber;
NSString *gThree = #"three"+iNumber;
NSString *gFour = #"four"+iNumber;
NSMutableArray *goodValues = [NSMutableArray arrayWithObjects:gOne,gTwo,gThree,gFour,nil];
return goodValues;
}
// ViewController.m
addons *directions =[[addons alloc]init];
NSMutableArray *helloTest = [[NSMutableArray alloc]init];
helloTest = [directions goodDirections:3];
NSString *obj1 = [helloTest objectAtIndex:1];
NSLog(#"%#",obj1);
and the custom class has a variable number, when entered returns an array with 4 string values, how do I retrieve the values from the array in my implementation file viewController.m
Make sure you import the custom class in the file you want.Then
NSMutableArray *arr = [theObject simpleMethod:4];
To retrieve any object in arr, you can use objectAtIndex function (for example):
NSString *item = [arr objectAtIndex:1];
please! try below code snip
NSMutableArray *arr = [theObject simpleMethod:4];
obj = [arr objectAtIndex:0];
You can use array object at index.
NSMutableArray *arrayTemp = [self simpleMthod:2];
objTemp = [arrayTemp objectAtIndex:0];
Or You can use
for (int i=0; i<[arrayTemp count]; i++)
{
objTemp = [arrayTemp objectAtIndex:i];
}

Resources