NSObject is not storing in NSMutableArray in objective c [closed] - iphone

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have parsed data stored in an NSObject file. I then stored the object file in an array:
[array addobject: object];
When i print the array, it only contains the first object value.
I declared the array globally, alloced memory for it and allocated memory for the object too.
It is printed like this:
array count 2 and array is:
(
"about 1st orders",
"about 2nd orders"
)
class is __NSArrayM
Previously it is correctly storing entire objects.
Any ideas or suggestions to solve this?

Following is describe Logic for You , might be helpful in you case.
First Create one class (name As you want)
#import <Foundation/Foundation.h>
#interface MyClassName : NSObject {
NSString *name; // set as per your requirement.
NSString *address; // set as per your requirement.
.
.
.
}
#property (retain, readwrite) NSString * name;
#property (retain, readwrite) NSString * address;
.
.
.
and Properly #synthesize and release reference. (if Not use ARC)
And add your array in this Class Object And then Get Data such like,
EDIT:
NSMutableArray *anOtherArray = [[NSMutableArray alloc] init];
for(int i=0; i < listOfArray.count; i++)
{
MyClassName *myData = [self.listOfArray objectAtIndex:i];
NSLog(#"%#", myData.name);
NSLog(#"%#", myData.address);
[anOtherArray addObject:myData.name];
[anOtherArray addObject:myData.address];
}

What is the definition of your object that you're storing in the NSArray? For custom objects being stored in an array, you should override NSObject's isEqual method.
For custom objects being stored in maps such as NSDictionary, you'll want to implement hashcode too.

Here is what i usually do when putting objects into array :
#import <Foundation/Foundation.h>
#interface ImageObject : NSObject
{
NSString *ImageURL;
NSString *Date;
// put any other stuff here.
}
#property (nonatomic, strong) NSString *ImageURL;
#property (nonatomic, strong) NSString *Date;
// put any other stuff here too.
#end
Then when you want to insert the object :
NSMutableArray *yourMutableArray = [[NSMutableArray alloc]init];
NSArray *array = [[NSArray alloc]initWithArray:[self.imageDictionary objectForKey:#"images"]];
for (NSDictionary *dict in array) {
ImageObject *imgObj = [[ImageObject alloc]init];
imgObj.ImageURL = [dict objectForKey:#"ImageURL"];
imgObj.Date = [dict objectForKey:#"LogDate"];
[yourMutableArray addObject:imgObj];
}
and for calling the items inside the array :
ImageObject *imgObj = [[ImageObject alloc]init];
imgObj = [yourMutableArray objectAtIndex:indexOfArray];

Related

NSMutableDictionary + NSMutableArray crash

I have an NSMutableDictionary called "myScheduleFullDictionary" set up like this:
KEY VALUE
"Day 1" An NSMutableArray of NSMutableDictionaries
"Day 2" An NSMutableArray of NSMutableDictionaries
"Day 3" An NSMutableArray of NSMutableDictionaries
etc.
I'm trying to parse it - basically grab one of the MutableArrays contained as the Value of one of the Keys.
Here is my code:
// First I make a mutableCopy of the entire Dictionary:
NSMutableDictionary *copyOfMyScheduleDictionary = [myScheduleFullDictionary mutableCopy];
// Next I grab & sort all the KEYS from it:
NSArray *dayKeysArray = [[copyOfMyScheduleDictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
// I set up an NSMutableArray to hold the MutableArray I want to grab:
NSMutableArray *sessionsInThatDayArray = [[NSMutableArray alloc] init];
// Then I iterate through the KEYs and compare each to the one I'm searching for:
for (int i = 0; i < [dayKeysArray count]; i++) {
NSString *currentDayKey = [dayKeysArray objectAtIndex:i];
if ([currentDayKey isEqualToString: targetDayString]) {
NSLog(#"FOUND MATCH!!!");
// I log out the NSMutableArray I found - which works perfectly:
NSLog(#"found array is: %#", [copyOfMyScheduleDictionary objectForKey:currentDayKey]);
// But when I try to actually grab it, everything crashes:
sessionsInThatDayArray = [copyOfMyScheduleDictionary objectForKey:currentDayKey];
break;
}
}
The error I get is:
-[__NSDictionaryM name]: unrecognized selector sent to instance 0x1c5fb2d0
Not sure why its pointing out "name" as the "unrecognized selector." "name" is an NSString property of a "Session" class I declared and am working with - could that be related somehow?
Any insights?
EDIT:
Here is my "SessionObject" class definition:
#interface SessionObject : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSString *speaker;
#property (nonatomic, strong) NSString *location;
#property (nonatomic, strong) NSDate *startTime, *endTime;
#property (nonatomic, strong) NSString *notes;
#property (nonatomic, strong) NSString *dayOfConference;
#end
-[__NSDictionaryM name]: unrecognized selector sent to instance 0x1c5fb2d0
This means that you are trying to call name on an NSMutableDictionary where as you should have called it on an object of class SessionObject. Check the line where you are calling something like myObject.name or [myObject name] and see if myObject is of type SessionObject and not NSMutableDictionary.
Here __NSDictionaryM denotes the NSMutableDictionary type.
I'm not sure where your bug comes from - but what are you doing there? Why don't you just write
sessionsInThatDayArray = [myScheduleFullDictionary objectForKey:targetDayString];
??? That's what NSDictionary is there for - you don't search for things by hand, you just call the method to look up the key. Instead you copied the dictionary, you extracted all the keys, you sorted the keys, you iterated through them one by one until you found it - and then you called objectForKey!!!
Apart from that, in the debugger set a breakpoint on all Objective-C exceptions. It will stop when the offending code is called, so no need to search for a needle in the haystack.

How do I get out data from my NSDirectory (not just a property typo)?

I'm missing something simple I think, but been at it for days now without solving this. Even Started to create a "work-around" just to solve it for now, but still want to solve this the "right" way. Any suggestions? Thank's!
.
The problem:
Seems to be missing the class Adealer (get error "-[Adealer objectAtIndex:]: unrecognized selector sent to instance 0x8c5f8b0"), but I did the import Adealer.h to this "detailsVC". But it's not just a simple error of naming the property wrong (objectForKey:#"CustName" instead of "custname" etc - tested this a lot).
Also, I've got similar "listVC"s without a class like Adealer in them, that also transfer data the same way to the same "detailsVC" and they work just fine! Then I just get the data with calls like;
self.labelRestName.text = [restDetails objectForKey:#"CustName"];
Overview:
I got a tableViewController "listVC" that creates the data and show a list, then a ViewController "detailsVC" to show the details. The data (selected row object in "listVC" is transfered via a seque and "destVC.restGPSTransfer" (NSDictionary). The data arrives ok in the "detailsVC" and looks like this in the terminal;
dealerName = Uppsala Centrum Test
dealerAdressStreet = Dragarbrunnsgatan 55
dealerAdressZip = 75320
dealerAdressCity = Uppsala
dealerLongitude = 17.63893
dealerLatitude = 59.85856
dealerDistance2 = 8586398.000000
etc
.
Following the data:
"listVC"
1) First fetching data from web via a AFNetworking json object into an NSMutableArray "restFeed" - ok.
2) Then creating my own data to an NSMutableArray within this loop into a NSMutableArray "updatedDealers" - ok;
NSMutableArray *updatedDealers = [[NSMutableArray alloc]init];
while (i+1 < [_restFeed count]) {
i++;
// Get dealer position function here
// Get distance function here
// Then create my own data here (also #imported Adealer to "listVC";
Adealer *theDealer = [[Adealer alloc]init];
theDealer.dealerName = [[_restFeed objectAtIndex:i]objectForKey:#"CustName"];
theDealer.dealerLongitude = [[_restFeed objectAtIndex:i]objectForKey:#"long"];
theDealer.dealerLatitude = [[_restFeed objectAtIndex:i]objectForKey:#"lat"];
theDealer.dealerDistance2 = theDistance;
// etc...
// Check if data ok
NSLog(#"theDealer = %#",[theDealer description]);
// Don't add dealer object without positiondata to the new array
if (![theDealer.dealerLatitude isEqualToString:#""]) {
[updatedDealers addObject:theDealer];
}
3) Then I use NSSortdescriptor to sort the dealers in NSMutableArray "updatedDealers" into distance order and finally creates the new NSMutableArray "restFeed" with this; (also did "#synthesize dealerFeed = _dealerFeed;" in "listVC") - ok.
_dealerFeed = [NSMutableArray arrayWithArray:sortedContestArray];
4) The populating some tableViewCells with this array and it works just fine - ok.;
cell.cellDealerName.text = [NSString stringWithFormat:#"%#",[[_dealerFeed objectAtIndex:indexPath.row]dealerName]];
5) In the function didSelectRowAtIndexPath transfer the selected object with the "detailsVC"'s NSDictionary "restGPSTransfer" - ok;
destVC.restGPSTransfer = [_dealerFeed objectAtIndex:myIndexPath.row];
"detailsVC":
6) The data seems to transfer ok (se top of this post) but when trying to call the data with;
self.labelRestName.text = [restGPSTransfer objectForKey:#"dealerName"];
I get this error and the app crashes: "-[Adealer objectAtIndex:]: unrecognized selector sent to instance 0x8c5f8b0".
Some more testing done...
Tried to verify the structure + it's keys and properties of the NSDictionary "restGPSTransfer", but using description only got me so far. And have not solved my problem and I still get the "unrecognized selector" error. Could it maybe have become dictionaries within dictionary's or something?
Constructed this little simple if-test to see if the property is really there. But I have to check every property "manually". There's propably a smarter way to check the hole NSDictionary / NSArray?
if ([restGPSTransfer objectForKey:#"dealerName"]) {
NSLog(#"= YES! key exists.");
} else {
NSLog(#"= Nope! key don't exists");
}
THANK'S for any help on this :-)
.
UPDATE the Adealer class files;
Adealer.h
#import <Foundation/Foundation.h>
#interface Adealer : NSObject
#property (nonatomic, retain) NSString * dealerName;
#property (nonatomic, retain) NSString * dealerAdressCity;
#property (nonatomic, retain) NSString * dealerAdressStreet;
#property (nonatomic, retain) NSString * dealerAdressZip;
#property (nonatomic, retain) NSNumber * dealerID;
#property (nonatomic, retain) NSString * dealerImages;
#property (nonatomic, retain) NSString * dealerLogo;
#property (nonatomic, retain) NSString * dealerMail;
#property (nonatomic, retain) NSString * dealerProducts;
#property (nonatomic, retain) NSString * dealerTel;
#property (nonatomic, retain) NSString * dealerText;
#property (nonatomic, retain) NSString * dealerWeb;
#property (nonatomic, retain) NSString * dealerLongitude;
#property (nonatomic, retain) NSString * dealerLatitude;
#property (nonatomic, retain) NSString *dealerDistance;
#property float dealerDistance2;
#end
Adealer.m
#import "Adealer.h"
#implementation Adealer
#synthesize dealerAdressCity, dealerAdressStreet, dealerAdressZip, dealerID, dealerImages, dealerLogo;
#synthesize dealerMail, dealerName, dealerProducts, dealerTel, dealerText, dealerWeb;
#synthesize dealerLongitude, dealerLatitude, dealerDistance,dealerDistance2;
- (NSString *)description {
// Added extension of description
NSMutableString *string = [NSMutableString string];
[string appendString:#"\ntheDealer object and it's properties:\n"];
[string appendFormat:#"dealerName = %#\n", dealerName];
[string appendFormat:#"dealerAdressStreet = %#\n", dealerAdressStreet];
[string appendFormat:#"dealerAdressZip = %#\n", dealerAdressZip];
[string appendFormat:#"dealerAdressCity = %#\n", dealerAdressCity];
[string appendFormat:#"dealerTel = %#\n", dealerTel];
[string appendFormat:#"dealerMail = %#\n", dealerMail];
[string appendFormat:#"dealerWeb = %#\n", dealerWeb];
[string appendFormat:#"dealerLogo = %#\n", dealerLogo];
[string appendFormat:#"dealerImages = %#\n", dealerImages];
[string appendFormat:#"dealerText = %#\n", dealerText];
[string appendFormat:#"dealerProducts = %#\n", dealerProducts];
[string appendFormat:#"dealerLongitude = %#\n", dealerLongitude];
[string appendFormat:#"dealerLatitude = %#\n", dealerLatitude];
[string appendFormat:#"dealerDistance = %#\n", dealerDistance];
[string appendFormat:#"dealerDistance2 = %f\n\n", dealerDistance2];
return string;
}
#end
SOLVED!
Posted if anyone else needs it here.
The solution
In my "detailsVC" I first did this iVar declaration;
.h:
Adealer *theDealer;
#property (nonatomic, retain) Adealer *theDealer;
.m:
#synthesize theDealer;
Then in my "listVC" i did this to transfer the Adealer object and it's properties to the "detailsVC" (remember that the Adealer object already has got it's properties earlier in the described "loop");
Instead of my earlier;
destVC.restGPSTransfer = [_dealerFeed objectAtIndex:myIndexPath.row];
I changed it to;
destVC.theDealer = [_dealerFeed objectAtIndex:myIndexPath.row];
And to actually show and check the transferred property in "detailsVC" I can now simply call this to get the dealers name (or any other properties);
self.labelRestName.text = theDealer.dealerName;
NSLog(#"theDealer.name = %#",theDealer.dealerName);
Works great! Happy Coding everyone!

instanced variable accessed in class method, Objective C

This is the original codes when I am getting this error
ClassA.h
+(ClassA*)methodA:(NSData*)data;
#property (nonatomic, strong) NSMutableArray *arr;
#property (nonatomic, strong) RXMLElement *rxmlRoot;
#end
ClassA.m
+(ClassA*)methodA:(NSData*)data {
//NSLog(#"class is %#",[name class]);
ClassA *ClassA = [[Stores alloc] init];
arr = [NSMutableArray array];
rxmlRoot = [RXMLElement elementFromXMLData:data];
}
I am reviewing my codes and now I have tow options to fix the code
OptionA
ClassA.h
+(ClassA*)methodA:(NSData*)data;
#property (nonatomic, strong) NSMutableArray *arr;
#property (nonatomic, strong) RXMLElement *rxmlRoot;
#end
ClassA.m
+(ClassA*)methodA:(NSData*)data {
//NSLog(#"class is %#",[name class]);
ClassA *ClassA = [[Stores alloc] init];
ClassA.arr = [NSMutableArray array]; <----- this has been modified
ClassA.rxmlRoot = [RXMLElement elementFromXMLData:data];<----- this has been modified
}
OptionB
ClassA.h
+(ClassA*)methodA:(NSData*)data;
#end
ClassA.m
static RXMLElement *rxlRoot; <----- this has been added as class variable
static NSMutableArray *arr; <----- this has been added as class variable
+(ClassA*)methodA:(NSData*)data {
//NSLog(#"class is %#",[name class]);
ClassA *ClassA = [[Stores alloc] init];
arr = [NSMutableArray array];
rxmlRoot = [RXMLElement elementFromXMLData:data];
}
I try either optionA or optionB and the compiler does not complain anything and the codes work properly.
I see many posts following the optionB which create class variables.
Question: is optionA also a good way to follow when we are dealing with class method and class variable as well.
Please advice me on this issue and by the way if I have made mistakes somewhere, please correct me. Thanks
There is no such thing as a "class variable" in Objective-C. When you declare a variable as static it is, effectively, a global variable that is limited to either the scope of the file it is compiled within or the scope of a method/function (or sub-expression).
Get rid of the Class. part of your calls to set the variables; that'll work in the .m file for the Class only; which is generally the pattern you would want (truly global variables are generally discouraged -- sometimes useful, though).
Create a designated initializer with a data parameter. Every class should have a designated initializer.
In your class method call the designated initializer passing in data.
Here is example code:
//ClassA.h
#class RXMLElement;
#interface ClassA : NSObject
+(ClassA*)methodA:(NSData*)data;
-(id)initWithData:(NSData*)data;
#property (nonatomic, strong) NSMutableArray *arr;
#property (nonatomic, strong) RXMLElement *rxmlRoot;
#end
//ClassA.m
#implementation ClassA
#synthesize arr;
#synthesize rxmlRoot;
+(ClassA*)methodA:(NSData*)data {
return [[ClassA alloc] initWithData:data];
}
-(id)initWithData:(NSData*)data {
self = [super init];
if (self) {
arr = [NSMutableArray array];
rxmlRoot = [RXMLElement elementFromXMLData:data];
}
return self;
}
#end
ARC is assumed in the example.

objective c interface access

this my first interface in a.h file.
#interface EventRow : NSObject
{
NSString *title;
NSString *photo;
NSString *description;
NSMutableArray *photoArray;
}
#property (nonatomic , retain) NSString *title;
#property (nonatomic , retain) NSString *photo;
#property (nonatomic , retain) NSString *description;
#property (nonatomic , retain) NSMutableArray *photoArray;
#end
in the same file second
#interface PhotoRow : NSObject
{
//NSString *image;
NSMutableArray *imageArray;
}
#property (nonatomic , retain) NSMutableArray *imageArray;
#end
Now every object of "PhotoRow" with filled array(imageArray) stored into the "photoArray" array in EventRow's object.
Now I want to count the total elements of "imageArray" . But getting problem in access it through the EventRow's object.
any suggestions ?
Thanks..
To access the individual objects in photoArray (eventRow is an instance of EventRow
[[eventRow photoArray] objectAtIndex: someIndex]; // I don't like dot notation!
or
[eventRow.photoArray objectAtIndex: someIndex];
To access the imageArray
[[[eventRow photoArray] objectAtIndex: someIndex] imageArray];
or
[eventRow.photoArray objectAtIndex: someIndex].imageArray;
To get the count of images for that imageArray
[[[[eventRow photoArray] objectAtIndex: someIndex] imageArray] count];
or
[eventRow.photoArray objectAtIndex: someIndex].imageArray.count;
If you want to count all of the images, you need loops but you can use fast enumeration to simplifiy things
size_t total = 0;
for (PhotoRow* photoRow in [eventRow photoArray])
{
total += [[photoRow imageArray] count];
}
However, I'd like you to rethink your design a bit. Your exposure of the NSMutableArray in each class breaks encapsulation. Once a caller has got hold of the array, it can modify the internal state of a PhotoRow or an EventRow without the object knowing about it. It would be better not to have the NSMutableArray properties but to add methods to add images and photoRows directly to PhotoRows and EventRows respectively. So, for instance your photoRow class might have the following methods:
-(size_t) imageCount; // returns the result of sending -count to the internal array
-(NSImage*) imageAtIndex: (size_t) index; // returns the result of sending -objectAtIndex: to the underlying array
-(void) addImage: (NSImage*) newImage;
// etc
If I understand you correctly, your photoArray variable in your EventRow class contains PhotoRow objects. You can count the objects in the PhotoRows imageArray variable like so:
int someIndex = 0;
[((PhotoRow*)[myEventRow.photoArray objectAtIndex:someIndex]).imageArray count];

NSMutableArray crashes when adding after proper initialization

I have an NSMutableArray defined as a property, synthesized and I have assigned a newly created instance of an NSMutableArray. But after this my application always crashes whenever I try adding an object to the NSMutableArray.
Page.h
#interface Page : NSObject
{
NSString *name;
UIImage *image;
NSMutableArray *questions;
}
#property (nonatomic, copy) NSString *name;
#property (nonatomic, retain) UIImage *image;
#property (nonatomic, copy) NSMutableArray *questions;
#end
Page.m
#implementation Page
#synthesize name, image, questions;
#end
Relevant code
Page *testPage = [[Page alloc] init];
testPage.image = [UIImage imageNamed:#"Cooperatief leren Veenman-11.jpg"];
testPage.name = [NSString stringWithString:#"Cooperatief leren Veenman-11.jpg"];
testPage.questions = [[NSMutableArray alloc] init];
[testPage.questions addObject:[NSNumber numberWithFloat:arc4random()]];
The debugger reveals that the moment I use testPage.questions = [[NSMutableArray alloc] init]; the type of testPage.questions changes from NSMutableArray* to __NSArrayL* (or __NSArrayI*, not sure). I suspect this to be the problem, but I find it extremely odd. Anyone know what's happening here?
The problem is that you've declared the property as copy. This means your setter is going to be implemented something like this:
- (void) setQuestions:(NSMutableArray *)array {
if (array != questions) {
[questions release];
questions = [array copy];
}
}
The kicker here is that if you -copy an array (whether immutable or mutable), you will always get an immutable NSArray.
So to fix this, change the property to be retain instead of copy, and also fix this memory leak:
testPage.questions = [[NSMutableArray alloc] init];
It should be:
testPage.questions = [NSMutableArray array];
#property (nonatomic, copy) This setter declaration "copy" probably cast to NSArray why not retain or assign? I would retain anyway
You can also create a mutable copy method like so:
- (void)setQuestions:(NSMutableArray *)newArray
{
if (questions != newArray)
{
[questions release];
questions = [newArray mutableCopy];
}
}