Unable to add NSmutableDictionary in NSmutable Array - iphone

Unable to add NSmutableDictionary in NSmutableArray, activitiesFeedArray is a mutable array and initialized in header file.
NSMutableDictionary *dummyitem = [[NSMutableDictionary alloc]init];
NSMutableDictionary *dummyitem2 = [[NSMutableDictionary alloc]init];
NSMutableDictionary *dummyitem3 = [[NSMutableDictionary alloc]init];
[dummyitem setObject:#"No Data Found" forKey:#"text"];
[dummyitem2 setValue:dummyitem forKey:#"Title"];
[dummyitem3 setObject:dummyitem2 forKey:#"ItemInfo"];
NSLog(#"%#",dummyitem3);
//dummyitem3 logs correct value here
if ([activitiesFeedArray count] == 0)
{
NSLog(#"%#",dummyitem3);
//dummyitem3 logs correct value here
[activitiesFeedArray addObject:dummyitem3];
NSLog(#"%#",activitiesFeedArray);
//activitiesFeedArray logs null value here
}
Viewdid load
(void)viewDidLoad
{
[super viewDidLoad];
activitiesFeedArray = [[NSMutableArray alloc]init];
}
Header File
#interface SearchViewController : UIViewController <UISearchBarDelegate ,UITableViewDelegate , UITableViewDataSource>
{
NSMutableArray *activitiesFeedArray;
}
#end

You don't mention where that code is, but it's clearly running some time before viewDidLoad, so the array is stil nil.

If this is the only code you have, then it should work fine and NSLog of your NSMutableArray should not return nil. I copied and pasted your code on my XCode and it works perfectly. You must be doing something somewhere else in your code to alter NSMutableArray.
If you are curious what I did to prove that your code works, I created a simple UIViewController with one button in it. I then created a UIViewController class and literally copied your code in the header file and the implementation file. I declared the NSMutableArray in the header file and initialized it in viewdidload (I copied and pasted them as is). I also put the rest of your NSMutableDictionary code in the viewDidLoad and it produced sensible results. The NSMutableArray log shows that it contains the correct data.
Sometimes it helps to do a clean build but as far as I can tell you, your code is correct and should work.
By the way, I have IOS5 and XCode 4.2.

Replace [dummyitem2 setValue:dummyitem forKey:#"Title"]; with [dummyitem2 setObject:dummyitem forKey:#"Title"];

Related

Why I can't access NSMutable Array in my method?

I try to add object to my NSMutable array in my method, but keep getting error. It works, if I add the object in init. It doesn't say that anything is wrong until I try to execute the code.
This is below the #import stuff where I declare two arrays:
NSMutableArray *actions1, *actions2;
This is in init:
actions1 = [NSMutableArray array];
Here I try to add 1 to the array:
- (void) storeAction:(int) action {
[actions1 addObject:#"1"];
}
The same code works in int as I said earlier.
I also would like it to store the int value declared "action", but this didn't seem to work either.
[addObject:#"%d", action];
[NSMutableArray array]; is returning an autoreleased object, by the time you try to access it, it is most likely deallocated already. Try [[NSMutableArray alloc] init]; instead. And than you should urgently check the memory management rules.
Try out this code
actions1 = [[NSMutableArray alloc] init];
Hope this helps.
Alternatively, in your header file:
#property(nonatomic, strong)NSMutableArray *actions1;
Then in the implantation file:
#synthesize actions1 = _actions1;
Then you can access your array as self.actions1.

read from plist and load into image name/label text

I have no idea where this code is wrong. Please help, it is supposed to read a value from a dictionary and I use the value to call an image. I've tried to read the value as label.text but I got no result.
The only one I can call is from the nslog.
for (id key1 in dictionary)
{
NSMutableString *textnamed = [dictionary objectForKey:key1];
NSMutableString *imageDisplay =[NSMutableString stringWithFormat:#"%#.png",[dictionary objectForKey:key1]];
eyeImageSaved.image = [UIImage imageNamed:imageDisplay];
labelSaved.text = textnamed;
NSLog(#"%#",textnamed);
}
There are a few issues with your code. First of all, you should consider using NSString instead of NSMutableString because it should be faster. Second, why are you putting the dictionary object in a string then calling the dictionary object again in the next line? That first line is unnecessary. It's entirely possible that the dictionary entry is not a string, and that is why you are having issues. You should write it like this NSString *textnamed = (NSString *)[dictionary objectForKey:key1]. Also, imageNamed can only be used for files in the file bundle. Are you sure those pictures are stored there? There are a few other issues you could be having. What exactly is going wrong here?
I solved my problem. There is nothing wrong with my code above, the mistake I made is that the object that is supposed to hold my variable and store in plist as the name of the image became null. So I added the object to appdelegate.h as seen below:
AppDelegate
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSString *imageNameHolder;
}
#property (retain, nonatomic) NSString *StorageDecider;
View Controller
- (IBAction)lips2:(id)sender {
imageNameHolder = #"lips_blue";
}
-(void)writeNewPlist
{
AppDelegate* ref = (AppDelegate*) [[UIApplication sharedApplication] delegate];
[dictionary setObject:imageNameHolder forKey:#"image1"];
[dictionary writeToFile:finalPath atomically:YES];
}
nameDataFormArray_ & imageDataFormArray_ are NSMutableArray. Both have string and find image as per string (name of image).
- (void)readInfoFromThePlist
{
NSString* PListPath=[[NSBundle mainBundle] pathForResource:#"dataList" ofType:#"plist"];
NSMutableArray* tempDataList=[[NSMutableArray alloc ] initWithContentsOfFile:PListPath];
for(NSDictionary *dataDict in tempDataList)
{
[nameDataFormArray_ addObject:[dataDict objectForKey:#"name"]];
[imageDataFormArray_ addObject:[dataDict objectForKey:#"imagepath"]];
}
[tempDataList release];
}

Issue loading plist into NSArray on ViewDidLoad

I'm trying to load a simple plist file in XCode 4 for an iPad application. The goal being that it will be loaded into the table portion of a split-view.
My project structure and plist look as follows:
I then declare an array in the interface of the RootViewController:
#import <UIKit/UIKit.h>
#class DetailViewController;
#interface RootViewController : UITableViewController {
NSArray *sites;
}
#property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
#end
I then, on viewDidLoad, attempt to load in the plist:
- (void)viewDidLoad
{
[super viewDidLoad];
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
NSBundle *bundle = [NSBundle mainBundle];
//NSLog(bundle);
NSString *path = [bundle pathForResource:#"StoredSites" ofType:#"plist"];
NSLog(path);
sites = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(#"%d", [sites count]);
}
The NSLog statements first return what appears to be the valid path, but upon try to load the NSArray with the contents of the file, it comes back with a count of 0:
I checked in the build phases to see if the file reference appears, and it seems to be ok:
I know this must be a simple problem, but for some reason I'm not seeing what's missing!
I appreciate the help -
You may want to using an NSDictionary, as that is what the sample code given here for the method pathForResource:ofType: uses.
I'm not entirely sure why it isn't working with an NSArray, but maybe the plist isn't formatted entirely correctly? The documentation for NSArray says that initWithContentsOfFile: takes in as a parameter quote:
The path to a file containing a string representation of an array
produced by the writeToFile:atomically: method.
Again, I'm not really sure. Hope that Helps!
The problem was the plist XML was wrapped in a dictionary rather than just being a simple array of arrays -
DShah covers it here: plist in xcode creation problem

how to preserve array outside of method in objective c

After a ASIFormDataRequest , i create a temporary NSMutableArray *resultArray from the JSON then add it to a defined NSMutablearray *myData
-(void)viewDidLoad{
myData = [[NSMutableArray alloc] init];
//request that calls gotInfo method
}
-(void)gotInfo:(ASIFormDataRequest *)request{
NSString *responseString = [request responseString];
NSMutableArray *resultArray = [responseString yajl_JSON];
[myData addObject:resultArray];
}
-(IBAction)doSomethingWithData:(id)sender{
//something with myData
}
but when i try to call myData from outside of the gotInfo: method, i get bad access errors and when i inspect myData outside of the method, it shows a kern_protection_failure. So i'm guessing that outside of the method, the resultArray is obviously released, but it's also released from myData since the object inside myData is sharing the same memory location?
I also tried
-(void)gotInfo:(ASIFormDataRequest *)request{
NSString *responseString = [request responseString];
[myData addObject:[responseString yajl_JSON]];
}
How do I preserve myData??
in my header file:
#import <UIKit/UIKit.h>
#class ASIFormDataRequest;
#interface EventsTableController : UITableViewController <UITableViewDataSource>{
NSMutableArray *myData;
}
-(void)gotInfo:(ASIFormDataRequest *)request;
UPDATE:
so in the gbd, the myData is allocated as 0x5e96560 so i did
po 0x5e96560
and then i get the EXC_BAD_ACCESS with the reason being KERN_PROTECTION_FAILURE at address: 0x00000009
but if i do
po [[0x5e96560 objectAtIndex:0] objectForKey:#"key"]
then i get the value! whyyyyyy?
#property(nonatomic,retain) NSMutableArray *myData
and create the object
self.myData = [[NSMutableArray alloc] init];
and
// and i assume your resultArray is a mature NSMutableArray object
[self.myData addObject:resultArray];
The best way of using copy I can think of, is to always set NSString properties to "copy" instead of retain. That way you get more accurate readings from the Leaks instrument if you mess up and forget to release a string an object is holding onto. Other uses of copy need to be more carefully thought out.
NOTE : You are responsible to release myData after no use of that variable.
You dont really have any way to correctly access myData as you declare it as a member inside of EventsTableController, but you dont set the #property for it, and do not synthesize it either. By synthesizing it in your EventsTableController.m file you are telling xcode to generate the getter/setters you need to correctly touch myData, which is where your program seems to be failing. If you do this, this should solve your problem.
-Karoly
Except for the different name of your ivar (mienVar vs. myVar), I don't see a problem. Some other code must be releasing your ivar, or you are accessing it before viewDidLoad has the opportunity to actually create the array (I bet it is the latter).
I think you should put the code in viewDidLoad in your initialization method instead. Don't forget to release the array in dealloc.
You could, of course, also write your own myData getter method, doing lazy initialization, instead of creating it in the init method:
- (NSMutableArray *) myData
{
if (!myData)
myData = [[NSMutableArray alloc] init];
return myData;
}
Note that now, you should access self.myData if you want to use it.
I think the NSString yajl_JSON category can return an array or a dictionary - you might need to inspect the type of the result array on the line below as it may be an NSDictionary:
NSMutableArray *resultArray = [responseString yajl_JSON];
IF you are treating it as an array when its a dictionary that might be causing your problems.
(relevant code from the NSObject+YAJL category below)
YAJLDocument *document = [[YAJLDocument alloc] initWithData:data parserOptions:options error:error];
id root = [document.root retain];
[document release];
return [root autorelease];
(and in YAJLDocument object)
#interface YAJLDocument : NSObject <YAJLParserDelegate> {
(id root_; // NSArray or NSDictionary

addObject to NSMutableArray not working for iPhone App

There have been a few threads on this topic but none have been able to solve my problem. Essentially I am trying to add a custom object to an NSMutableArray and it doesn't seem to be adding. I don't get any errors but I get a warning saying that my array is an "unused variable" so it looks like it is not getting used. See code below. Any help is appreciated!
Here is the initialization in the app delegate (on run time it says this array is not being used):
NSMutableArray *organArray = [[NSMutableArray alloc] init];
Here is my object class organ.m (I am importing the app delegate, the rootviewcontroller and the organ.h file)
Organ *organObj = [[Organ alloc] initWithPrimaryKey:primaryKey];
organObj.organName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,1)];
organObj.isDirty = NO;
[appDelegate.organArray addObject: organObj];
[organObj release];
I know the organObj.organName is getting the correct values from my sqlite db because I can output them to the console. They just don't seem to be getting added to the array and the fact that it says the array is not being used means something is wrong.
Thanks in advance
Just a guess but if organArray is intended to be a member of your app delegate, you are creating a new organArray when prefixing it with "NSMutableArray" so if I understand your code, change your app delegate to:
organArray = [[NSMutableArray alloc] init];
instead of:
NSMutableArray *organArray = [[NSMutableArray alloc] init];