Getting Null array - iphone

I have following code :
- (IBAction)goButton:(id)sender
{
if(buttonCount==0)
{
previousStateArray=setUpArray;
NSLog(#"previous array count=%d",[previousStateArray count]);
[setUpArray removeAllObjects];
for(Node *n in nodeArray)
{
if(![temp isEqualToString:n.strName])
{
[setUpArray addObject:n.strName];
}
temp=n.strName;
}
}
}
- (IBAction)backButton:(id)sender
{
[setUpArray removeAllObjects];
setUpArray=previousStateArray;
NSLog(#"previous array count=%d",[previousStateArray count]);
buttonCount--;
}
Both setUpArray and previousStateArray are declared in the -viewDidLoad method.My view is loading only once.In first NSLog i am getting 1 as a output but in second NSLog i am getting
0 as a output while none of my array initialize again . so why this is happening???

Your problem is with your array pointers.
In goButton :
previousStateArray=setUpArray;
Now previousStateArray points to the same array setUpArray is pointing to.
[setUpArray removeAllObjects];
This removes all objects and now both pointers point to an empty array.
In backButton:
setUpArray=previousStateArray;
They both point to the same empty array so this line is redundant.
You should keep a temporary pointer if you want to swap the pointers.

In your code
`previousStateArray=setUpArray;` //previousStateArray pointing to same memory location of setUpArray.
Use - (void)setArray:(NSArray *)otherArray method of NSMutableArray class.
[previousStateArray setArray: setUpArray];
[setUpArray setArray:previousStateArray];
- (IBAction)goButton:(id)sender
{
if(buttonCount==0)
{
[previousStateArray setArray: setUpArray];
NSLog(#"previous array count=%d",[previousStateArray count]);
[setUpArray removeAllObjects];
for(Node *n in nodeArray)
{
if(![temp isEqualToString:n.strName])
{
[setUpArray addObject:n.strName];
}
temp=n.strName;
}
}
}
- (IBAction)backButton:(id)sender
{
[setUpArray removeAllObjects];
[setUpArray setArray:previousStateArray];
NSLog(#"previous array count=%d",[previousStateArray count]);
buttonCount--;
}

Initialize the array
setUpArray = [[NSMuatableArray alloc] init];

I think giorashc's answer is correct.
Your problem is using "=" for Array only makes the new one previousStateArray points to the same memory of setUpArray. In other words, previousStateArray is the same as setUpArray .
For more detail information , you should search deep & shallow copy.

You should also use if(0 == buttonCount) rather than if(buttonCount==0).

Related

bool for key in NSMutableArray

I have a code like that
if ([dataArray valueForKey:#"success"]) {
[self.feedsArray addObjectsFromArray:dataArray];
NSLog(#"self.feedsArray: %#",self.feedsArray);
} else {
NSLog(#"no feed found ");
}
dataArray is a NSMutableArray which ultimately contains a JSON Dictionary.
but I am getting the same console output independent of success either TRUE or FALSE, but my console output is always same.my console output is:
for FALSE or NO:
self.feedsArray: (
{
action = register;
message = "Invalid parameters";
success = 0;
}
)
and for TRUE or YES:
self.feedsArray: (
{
action = register;
message = "valid parameters";
success = 1;
}
)
in both cases if part is executed.
in NSUserDefaults there is a method boolForKey but how to do this in case of NSMutableArray.
You need to read the fine print for [NSArray valueForKey:], specifically:
Returns an array containing the results of invoking valueForKey: using
key on each of the array's objects.
and:
The returned array contains NSNull elements for each object that
returns nil.
So if the array contains, say, 3 objects and none of them have a success key then you will get an array of 3 NSNull objects returned.
Therefore the if statement will fire whenever dataArray is non-empty, which is obviously not what you intended.
You should check the contents of the returned array:
BOOL succeeded = NO;
NSArray *results = [dataArray valueForKey:#"success"];
for (NSObject *obj in results) {
succeeded = [obj isKindOfClass:[NSNumber class]] && [(NSNumber *)obj boolValue];
if (succeeded)
break;
}
if (succeeded) {
[self.feedsArray addObjectsFromArray:dataArray];
NSLog(#"self.feedsArray: %#",self.feedsArray);
} else {
NSLog(#"no feed found ");
}
You can do this in simple way:
What i see in your response json value is, you have dictionary in dataArray at index 0
NSMutableDictionary *responseDict = [dataArray objectAtIndex:0];
if([[responseDict objectForKey:#"success"] boolValue])
{
NSLog(#"Success: 1");
}
{
NSLog(#"Success: 0");
}
Use index instead of key for an array.
NSDictionary dictionary = (NSDictionary *)dataArray[0];
if ([(NSNumber *)[dictionary objectForKey:#"success"] boolValue]) {
// ...
}
otherwise use if([[[dataArray objectAtIndex:0] valueForKey:#"success"] isEqualToString:#"1"])
An array does not store keys, the only way to access items in an array is by index.
You should be using an NSDictionary/NSMutableDictionary instead. If you want to use a bool store it as a NSNumber, [NSNumber numberWithBool:YES] and then use the instance method valueForBool to read it back.
Try this
if ([[dataArray valueForKey:#"success"]isEqualToString:#"1"]) {
[self.feedsArray addObjectsFromArray:dataArray];
NSLog(#"self.feedsArray: %#",self.feedsArray);
}
else {
NSLog(#"no feed found ");
}
It 'll work out.
use this if you want bool value
if([[dataArray valueForKey:#"success"] boolValue])
{
//i.e success is true
}
if response contains array of dictionaries then we can use loop and check condition,
here i is index variable of array,
if([[[dataArray objectAtIndex:i] objectForKey:#"success"] boolValue])
{
// success is true ,
}
Replace you code line
if ([dataArray valueForKey:#"success"]) {
}
with
if ([[dataArray valueForKey:#"success"] integerValue]) {
}
Hope it will work for you.
its working with replacing the line with
if ([[[dataArray objectAtIndex:0] valueForKey:#"success"] boolValue])

Object at index in NSArray

I have an array. I want to check whether there is an object present in a particular index or not. How to do this? Please help.
if you just want to check if there is an object
if (myIndex < [array count])
if you want to find a specific object
[array indexOfObject:myObject];
if you want to know if the object at some index is of some class
[[array objectAtIndex:myIndex] isKindOfClass:[TheClassToCompareTo class]];
BOOL exists = index < [array count] ? YES : NO;
You can use containsObject method to check weather your array contains the specific object or not. If contains, then get its index by indexOfObject method
if ([yourArrayArray containsObject:yourObject])
{
NSLog(#"Found");
int index = [yourArray indexOfObject:yourObject];
}
I know this is old thread but just trying to help.
You can add a category to NSArray something like this
#implementation NSArray (Safe)
- (id)safeObjectAtIndex:(NSUInteger)index {
if (index >= [self count]) return nil;
return [self objectAtIndex:index];
}
#end
You should check the length of the array (using the count method) and given NSArray cannot contain nil it must therefore contain something:
- (BOOL)arrayContainsSomethingAtIndex:(NSUInteger) index
{
return [_myArray count] > index;
}
Use indexOfObject: method.
if ([Array indexOfObject:object]==index) {
//code
}
check like this
if([array objectAtIndex:i]!= nil)
{
NSLog("Object present");
}
else{
NSLog("Object Not Present")
}
Modified:
You should make like this
if(i<=[array count]){
if([array objectAtIndex:i]!= nil)
{
NSLog("Object present");
}
else{
NSLog("Object Not Present")
}
}
This will not raise exception and object in array should compare with nil value
First you must check if the index of that object is smaller than the size of the array, then you query the array at that index.
if (index < [array count] && [array objetAtIndex:index]){
/* Your code*/
}

Printing array inside array

I have class Building in which i have one class member NSMutableArray *subnode.I have declared one more array buildingArray which stores the element of type Building.I have tried to print Building class object as shown in following code.But goes in only first for loop.
Second for loop of subnode array is not executing . Is this proper way of printing the object having the array as a one of its class member.
code:
for(Building *b in buildingArray)
{
NSLog(#"inside building array");
for(NSString *str in b.subnode)
{
NSLog(#"inside subnode array");
}
}
If this is for debugging purposes, I would recommend trying the following: Every object that inherits from NSObject inherits its description method.
Add this to Building.m:
#implementation Building
- (NSString *)description {
NSMutableString *description = [NSMutableString stringWithString:[super description]];
// add the following lines for any relevant properties
// [description appendFormat:#", materials == %#", materials];
// then have the subnode print itself:
[description appendFormat:#", subnode == %#", subnode];
return description;
}
#end
You can then print the entire buildingArray by simply calling the following code:
NSLog(#"buildingArray == %#", buildingArray);
for(Building *b in buildingArray)
{
NSLog(#"inside building array");
NSMutableArray *temp = [NSMutableArray arrayWithArray:b.subnode]
for(id *str in temp)
{
NSLog(#"inside subnode array");
}
}
this should work. happy coding :)
Your code seems to be ok. Just check if the array (subnode) is allocated and initialized. Also check if it has some values in it. I have used similar code and it works for me.
Change following code. I don't know what do you mean buy Building . So i just used id instead of Building to avoid any type of confusion.
for(id b in buildingArray)
{
NSLog(#"inside building array");
NSArray *temp = b;
for(NSString *str in temp)
{
NSLog(#"inside subnode array");
}
}
Hope, this will help you;

Copying NSMutableDictionary through pointers

What I'm trying to do is search an array of dictionaries for a specific target dictionary, and if found, replace the actual dictionary in the original array with the target dictionary. The search algorithim works, but the copying of dictionaries doesn't. The main line in question is the one that says:
tempDict=targetDict;
I was hoping that tempDict would be a pointer to the original dictionary from the original array, but when trying to log the author name, I get "moe" instead of "steve".
-(void)viewDidAppear
{
[actualDictionary setObject:#"test" forKey:#"mainNote"];
[actualDictionary setObject:#"moe" forKey:#"authorName"];
[targetDictionary setObject:#"test" forKey:#"mainNote"];
[targetDictionary setObject:#"steve" forKey:#"authorName"];
[arrayOfNotes addObject:actualDictionary];
[self beginSearchWithMainArray];
}
-(void)beginSearchWithMainArray;
{
[self searchArray:arrayOfNotes forDict:targetDictionary];
}
-(void)searchArray:(NSMutableArray*)array forDict:(NSMutableDictionary*)targetDict
{
NSString *targetText=[targetDict objectForKey:#"mainNote"];
for(int i=0;i<[array count];i++)
{
NSMutableDictionary *tempDict=[array objectAtIndex:i];
NSString *possibleText=[tempDict objectForKey:#"mainNote"];
if([possibleText isEqualToString:targetText])
{
//found match, replace tempDict with targetDict
tempDict=targetDict;
NSLog(#"found match");
NSString *authorName=[[arrayOfNotes objectAtIndex:0] objectForKey:#"authorName"];
NSLog(#"%#", authorName); //should be steve
return;
}
//no match, search sub notes
...
}
}
replace
tempDict=targetDict;
with
[array replaceObjectAtIndex:i withObject:targetDict];
or
[tempDict setDictionary:targetDict]
tempDict is a pointer to a NSMutableDictionary, but assign it to another instance doesn't means change the content of the previous instance
you have to modify what "pointer point to" not the "pointer", thats why you can use setDictionary: to do the "assignment"
tempDict is just a reference to the matched element of the array. Changing its value will not modify the array. Replace
tempDict=targetDict;
to
[array replaceObjectAtIndex:i withObject:targetDict];

How do I find (not remove) duplicates in an NSDictionary of NSArrays?

The title pretty much says it all, but just to clarify: I have an NSMutableDictonary containing several NSMutableArrays. What I would like to do is find any value that is present in multiple arrays (there will not be any duplicates in a single array) and return that value. Can someone please help? Thanks in advance!
Edit: For clarity's sake I will specify some of my variables:
linesMutableDictionary contains a list of Line objects (which are a custom NSObject subclass of mine)
pointsArray is an array inside each Line object and contains the values I am trying to search through.
Basically I am trying to find out which lines share common points (the purpose of my app is geometry based)
- (NSValue*)checkForDupes:(NSMutableDictionary*)dict {
NSMutableArray *derp = [NSMutableArray array];
for (NSString *key in [dict allKeys]) {
Line *temp = (Line*)[dict objectForKey:key];
for (NSValue *val in [temp pointsArray]) {
if ([derp containsObject:val])
return val;
}
[derp addObjectsFromArray:[temp pointsArray]];
}
return nil;
}
this should work
If by duplicates you mean returning YES to isEqual: you could first make an NSSet of all the elements (NSSet cannot, by definition, have duplicates):
NSMutableSet* allElements = [[NSMutableSet alloc] init];
for (NSArray* array in [dictionary allValues]) {
[allElements addObjectsFromArray:array];
}
Now you loop through the elements and check if they are in multiple arrays
NSMutableSet* allDuplicateElements = [[NSMutableSet alloc] init];
for (NSObject* element in allElements) {
NSUInteger count = 0;
for (NSArray* array in [dictionary allValues]) {
if ([array containsObject:element]) count++;
if (count > 1) {
[allDuplicateElements addObject:element];
break;
}
}
}
Then you have your duplicate elements and don't forget to release allElements and allDuplicateElements.