question on NSUserDefault Class - iphone

I have value in 1 string for particular key.
but NSUserDefault class method doesn't work properly and it doesn't set object of a string forkey .
in short setobject forkey method is not working of NSUserDefault class.
why is it so?

First of all, NSUserDefault class works just fine. It is called millions of times every day and works exactly as expected. The next likely culprit is your code. If you post that, it will be much easier to determine what you're doing wrong, and to make an appropriate suggestion.
(Edit added after OP's comment)
I just added this code:
//* TEST
NSString *string01 = #"Hardwork";
NSUserDefaults* defs111 = [NSUserDefaults standardUserDefaults];
[defs111 setObject:string01 forKey:#"first_name_textfield"];
NSString *test = [defs111 objectForKey:#"first_name_textfield"];
NSLog(#"Test: %#", test);
to my project and ran it and everything worked just fine.
As I stated above: NSUserDefault works like a champ. There's something you're not telling us about your use-case. Something important. ;)

Related

Strange behavior of NSString

I have a NSString that will be passed as a parameter to my library's function, the NSString is passed by another library. The strange thing is, if I pass the NSString to the library call, the call will fail, but if I convert the NSString to int and then convert the int back to a NSString, every thing is fine.
But by printing it out using NSLog("%#"), the two strings are identical. What may cause this? Encoding?
When you
convert the NSString to int and then convert the int back to a NSString
you are basically creating a copy of the string, unrelated to the original one.
It would be interesting to know how you create the two strings to know what exactly happens. My guess is that the first one is deallocated too soon, so the call fails; the copy is retained and the call succeeds.
Just for a quick try:
when calling the function that is failing:
[self doMethodWithString:aString];
just do:
[aString retain];
[self doMethodWithString:aString];
If this works, then the memory management issue is confirmed, but for a real fix you should explain how you create the strings...

NSUserDefaults: Question about difference between two approaches

Problem
I want to store a NSString in NSUserDefaults and retrieve it later. I have a question about two different retrieving methods. Now at the top of the file I have:
// String used to identify the update object in the user defaults storage.
static NSString * const kLastStoreUpdateKey = #"LastStoreUpdate";
Method 1
NSString *lastUpdate = [[NSUserDefaults standardUserDefaults] objectForKey:kLastStoreUpdateKey];
Method 2
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:kLastStoreUpdateKey];
Are there are significant differences I should know about? Also, can someone please explain what exactly is objectForKey? Apple's API states: that it "Returns the object associated with the first occurrence of the specified default." What exactly do they mean by the "specified default?
Thank you!
Generally you should use method 1.
that is "objectForKey".
Because, you know that, whatever you have stored in NSUserDefault. So, at the time of retriving it, you can catch the object with proper class like NSString, Array or any other user defined.
genrally "stringForKey" is not used.
If you are storing ingteger, BOOL into NSUserDefault then you should use intForKey, BOOLforKey, etc..
Cheers.

NSlog returns NULL for NSMutableDictionary from different class

Really confused with why this is not working.
PracticeTeamSelection.m
NSLog(#"Practice Roster : %#", practiceRoster);
PracticeActual.m
PracticeTeamSelection *teamSelectionViewController = [[PracticeTeamSelection alloc]init];
NSLog(#"practice List : %#", [teamSelectionViewController practiceRoster]);
So practiceRoster is an NSMutableDictionary, and when i run the first bit of code I am returned exactly what i am supposed to be, however when i run the next bit of code in PracticeActual.m it returns (Null).
in my PracticeTeamSelection in the .h I do the following with the proper synthesize
#property(nonatomic,retain) NSMutableDictionary *practiceRoster;
and in the PracticeActual.m in include
#import "PracticeTeamSelection.h"
But maybe it is being release somewhere with out my knowledge. Does anyone have any thoughts?
Thanks
You haven't actually created a dictionary anywhere. You just defined a property. All properties on an object start out with their zero value — for objects, this is nil.
You have one PracticeTeamSelection object where practiceRoster is set to something. But in your PracticeActual class, when you write [[PracticeTeamSelection alloc]init], you're creating another PracticeTeamSelection object. The new object has nothing to do with the other one that has its practiceRoster set, no more than all your NSString objects have the same content.

Where to initialize an instance variable in a class

I'm new to objective-c and I always have problem with global variable . I don't know where to initialize them . My problem is with an NSString . I wrote this code –
in .h
NSString *session ; // i also #property(retain,nonatomic) and synthesize ...
in viewDidLoad , '
session=#"HEllo";
and in
-(IBAction) showInformations:(id)sender;
{
NSLog(#" informations ok");
NSLog(#"my sesison : %# ",session);
}
But I have a crash in show information :/ session is empty I think . Help please
session = #"hello";
self.session = #"hello";
There is a huge difference between the above two statements. The first one just assigns hello to session. Here the string hello is autoreleased, so session is not valid when you tap the button, as you have not retained session. But in 2nd line self is used. When self is used, it is not just a simple assignment, it is actually a call to accessor method. Here you have used retain in property declaration. So when self is used, the setter for session is called which retains it. So session is valid when you tap the button.
The summery is use right property and use self to avoid many memory problems.
EDIT: As pointed by fluchtpunkt, this explanation is not valid for string literals. I was out of my mind that string literals are special when writing this.
Try setting it using the dot syntax for a property:
self.session=#“Hello”;
This will ensure proper memory management.
There must be another write access to session somewhere in your code. A line of code that looks like session = [NSString stringWith...];
So find the other parts of the code where you assign something to the session variable and replace the wrong memory management over there with proper memory management. The problem is not within the three lines you have shown.
Depending on your code it should be something like
self.session = [NSString stringWith...
or if you like it inconvenient
[session release];
session = [[NSString stringWith...] retain];

iPhone SDK mem management issues - EXC_BAD_ACCESS

I've been staring at this same issue for a long time now, and would really appreciate any help or suggestions. I'm sure its something simple, but I can't seem to find it. In my app delegate I'm loading up a bunch of accessory objects (an object I created, which supports NSCopying) with the following code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Accessories" ofType:#"plist"];
NSDictionary *accDict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.colors = (NSArray *) [accDict objectForKey:#"Colors"];
self.exteriorAccessories = [self loadAccessoriesForMode:EXTERIOR_MODE withDictionary:accDict];
self.interiorAccessories = [self loadAccessoriesForMode:INTERIOR_MODE withDictionary:accDict];
[accDict release];
And this is the definition for the method its calling:
-(NSArray *)loadAccessoriesForMode:(NSString *)mode withDictionary:(NSDictionary *) dictionary
{
NSMutableArray *tempValues = [[NSMutableArray alloc] init];
for (NSDictionary *value in [dictionary objectForKey:mode])
{
Accessory *accessory = [[Accessory alloc] initWithDictionary:value];
[tempValues addObject:accessory];
[accessory release];
}
NSArray *returnArray = [[NSArray alloc] initWithArray:tempValues copyItems:YES];
[tempValues release];
[returnArray autorelease];
return returnArray;
}
When I get to the release for accDict I'm getting an EXC_BAD_ACCESS exception. If I take out the release of accessory inside the loop, everything is fine - but I'm leaking Accessory objects (which seems obv. to me - if I init it and I alloc it, its my job to release it).
When I step through this in the debugger, I'm seeing the init, copy and dealloc methods all fire on my Accessory object as expected. I can also post code for the Accessory object if you think it will help, but I think the problem is somewhere in this code.
I think I've found the cause, but I'll post it here so others can possibly benefit. It didn't really have anything to do with the code I posted. Rather the problem was inside of the Accessory object. I was setting things directly instead of calling the getters through self.
So this:
value = [dict objectForKey:#"myKey"];
Instead of this:
self.value = [dict objectForKey:#"myKey"];
Somehow this was causing me to have bad side effects on the NSDictionary itself (I thought that was not mutable, but it seems I was somehow messing things up). The only way I found this was to use the very helpful advice that I found on Cocoa With Love.
When I used the Print Description option in XCode, I was able to see that the NSDictionary somehow contained AccessoryValue objects - one of my custom objects that should NOT have been there since this was just loaded from a simple plist. Print Description can be found in XCode by hovering over the object to see its details (while the process is paused in the debugger) and clicking on the little up/down arrows right next to the triangle that expands into object details. For dictionaries, this will dump their entire contents to the console.
Please prefix this with an "I know nothing about objective C but":
It looks to me like you need to release the accessory items after you have copied them into the "returnArray", or maybe not specify "copyItems".
Run Clang on your code. It's a godsend. Clang rules! It will do Static Analysis of your code and tell you what you might be leaking. Great stuff.
I was battling with the Exc_Bad_Access issue for a day and finally found the answer. The issue was when I try to access one of the objects stored in an NSDictionary, the first time was OK but the second access the object turned to be nil even though the object counts in the dictionary remains the same. This strange behavior was due to releasing the object twice. Here is an example:
NSString* nstring=[[[NSString alloc]init]autorelease]
[AnNSDictonaryInstance setObject:nstring forKey:0];
...
[nstring release];
Notice that nstring was set autorelease then release again? It won't show problem right away unit you try to read the dictionary object the second times. I hope one day Apple's development team will be able to flag this as an violation while compiling.
I hope this post will help someone out.
Wayne of Campbell