NSString function - iphone

I get a null return when i try out my NSString function.
//Track.m
static NSString* trackUrl;
//static NSString* getTrackNumberUrl;
#implementation Track
- (NSString*)trackUrl {
return #"http://site.com/?a=";
}
- (NSString*)setTrackNumberUrl:(NSString*)trackNumberUrl {
if (trackUrl != trackNumberUrl) {
return [trackUrl stringByAppendingFormat:trackNumberUrl];
}
return #"Error no trackNumber";
}
- (NSString*)getTrackNumberUrl:(NSString*)trackNumber {
return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease];
}
#end
MainView.m, just to show the return answer in NSlog
- (NSString *) trackNumber{
return [track getTrackNumberUrl:#"86147224549XX"];
}
- (void)drawRect:(CGRect)rect {
NSLog(trackNumber);
}
I get a null return answer? Have i miss something? Thanks.
Edit some in Track.m
- (NSString*)setTrackNumberUrl:(NSString*)trackNumberUrl {
if (trackUrl != trackNumberUrl) {
return [trackUrl stringByAppendingString:trackNumberUrl];
}
return #"Error no trackNumber";
}
- (NSString*)getTrackNumberUrl:(NSString*)trackNumber {
return [[[Track alloc] setTrackNumberUrl:trackNumber] init];
}
This is how it should work.
getTrackNumberUrl --> setTrackNumberUrl --> trackUrl (return) --> setTrackNumberUrl + trackNumber --> getTrackNumberUrl (trackNumberUrl = trackUrl + trackNumber)
I have this code to set reference to Track
#class Track;
#interface MainView : UIView {
Track *track;
}
#property (nonatomic, retain) IBOutlet Track *track;
Well if don't should use self alloc, what should i use?

You have a lot of problems with your code.
return [trackUrl stringByAppendingFormat:trackNumberUrl];
You should not use an arbitrary string as a format, because if it contains a format specifier like "%d" then the method will go looking for a variable that isn't there, and will likely crash. You should use stringByAppendingString: instead. However, that doesn't seem to be what you want here, since the method name is setTrackNumberUrl:. If you want to change the value of the trackUrl variable, you can't call stringByAppendingFormat:; all that does is return a new string and leave the original alone. I think you simply want something like
[trackUrl release];
trackUrl = [trackNumberUrl retain];
Another problem:
return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease];
In this context, self is an instance of Track. An instance won't understand the alloc message, that must be sent to a class. It will return a new instance, to which you should send an init message. So you would do something like [[Track alloc] init].
NSLog(trackNumber);
The first parameter to NSLog is a format string, so for the same reasons as above you shouldn't use a variable, you should do something like this: NSLog(#"%#", trackNumber); That line of code prints the value of the variable, trackNumber. Considering that you have a method named trackNumber just above it, I wonder if what you really want to do is call the method and get the result. In that case, you need to write it as [self trackNumber] which will call the method and return an NSString.

Most probably track is nil in the trackNumber - have you set it to a correct reference to a Track object?
Also, this code
- (NSString*)getTrackNumberUrl:(NSString*)trackNumber {
return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease];
}
is incorrect. Why are you using [self alloc]? You're allocating a new Track object (using a static method on an object reference, not on a class name, which is an error), setting it's track number URL, and returning an autoreleased NSString, but you're leaking the Track object you allocated.

return [trackUrl stringByAppendingFormat:trackNumberUrl];
I'm not sure bout this one,
try using it as a format for string.
return [trackUrl stringByAppendingFormat:#"%#",trackNumberUrl];

Related

Is this the correct syntax, myField_ = [newValue retain]?

I'm trying to learn Objective C. I came across the following code which the compiler generates behind the scenes for #property(nonatomic, retain) NSString* myField
-(NSString*) myField
{
return myField_; //assuming myField_ is the name of the field.
}
-(void) setMyField:(NSString*) newValue
{
if(newValue != myField_)
{
[myField_ release];
myField_ = [newValue retain];
}
}
Now my question is; Why to call retain on newValue? Instead the following syntax should be used:
myField_ = newValue;
[myField_ retain];
Please advise why the above syntax is not used because as per my understanding, we want to retain the object pointed to by myField_ ?
They're the same (both are correct). You don't copy the object - retain returns the same pointer that was retained, so it's shorter and cleaner to write
ivar = [newObj retain];
than separately assigning and retaining the object.
Both syntaxes are correct. In the first case we also retain the object pointed by myField since we assign [newValue retain] to it.

Problem with allocating memory for an Objective-C data object

I've been programming objective-C for a few months now and have done pretty well so far without having to post any questions. This would be my first. The problem is that I'm getting a memory leak warning from a data object in one of it's methods. I can see that the problem is that I'm sending an alloc to it without releasing it, but I don't know how else to get it to retain the object in memory. If I take the alloc out, the program crashes. If I leave it in, it leaks memory. Here is the method in question:
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
newFeature.featureID = fID;
newFeature.featureName = fName;
newFeature.featureSecure = fSecure;
return [newFeature autorelease];
}
This method is called by another method in my view controller. This method is as follows:
+ (NSMutableArray*) createFeatureArray {
NSString *sqlString = #"select id, name, secure from features";
NSString *file = [[NSBundle mainBundle] pathForResource:#"productname" ofType:#"db"];
sqlite3 *database = NULL;
NSMutableArray *returnArray = [NSMutableArray array];
if(sqlite3_open([file UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = [sqlString UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
Feature *myFeature = [Feature featureWithID:sqlite3_column_int(compiledStatement,0)
name:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]
secure:sqlite3_column_int(compiledStatement,2)];
[returnArray addObject:myFeature];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return returnArray;
}
I have tried several things, such as creating a featureWithFeature class method, which would allow me to alloc init the feature in the calling method, but that crashed the program also.
Please let me know if you need any clarification or any other parts of the code. Thank you in advance for your help.
UPDATE: 4/14/2011
After reading the first two responses I implemented the suggestion and found that the program is now crashing. I am at a complete loss as to how to track down the culprit. Hoping this helps, I am posting the calling method from the view controller as well:
- (void)setUpNavigationButtons {
// get array of features from feature data controller object
NSArray *featureArray = [FeatureController createFeatureArray];
int i = 0;
for (i = 0; i < [featureArray count]; i++) {
Feature *myFeature = [featureArray objectAtIndex:i];
CGRect buttonRect = [self makeFeatureButtonFrame:[featureArray count] withMember:i];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setFrame:buttonRect];
[aButton addTarget:self action:#selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:[NSString stringWithFormat:#"%#",myFeature.featureName] forState:UIControlStateNormal];
aButton.tag = myFeature.featureID;
[self.view addSubview:aButton];
}
}
NOTE: These methods are posted in reverse of the order they are invoked. This last method calls the second method, which in turn, calls the first.
UPDATE: I've updated these functions to show what is in there now: Below, I will post the header files for the object - maybe that will help
#interface Feature : NSObject {
int featureID;
int featureSecure;
NSString *featureName;
}
#property (nonatomic, assign) int featureID;
#property (nonatomic, assign) int featureSecure;
#property (nonatomic, retain) NSString *featureName;
- (id) init;
- (void) dealloc;
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure;
#end
#interface FeatureController : NSObject {
}
- (id) init;
- (void) dealloc;
+ (NSMutableArray*) createFeatureArray;
+ (Feature*) getFeatureWithID:(int)fetchID;
#end
Convenience methods should follow the convention of returning autoreleased objects. Change this:
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
...
return newFeature;
}
to:
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
...
return [newFeature autorelease];
}
The name of your method - +featureWithID:name:secure: - indicates that it returns an object that the caller does not own. Instead, it is returning an object that has been retained, that the caller therefore owns and must release. To fix this (and your leak), simply replace return newFeature with return [newFeature autorelease].
There's nothing more you need to do, because your own code doesn't need a long-lasting ownership claim, and the array to which you're adding the object will manage its own ownership claim over it.
In +createFeatureArray, you’re over releasing the array:
+ (NSMutableArray*) createFeatureArray {
…
NSMutableArray *returnArray = [[[NSMutableArray alloc] init] autorelease];
…
return [returnArray autorelease];
}
In the first line, you used +alloc, so you own the array. Then you used -autorelease, so you do not own the array any more. This means that you shouldn’t send -release or -autorelease to it, which you are doing in the return line.
You can fix that by changing those lines to:
+ (NSMutableArray*) createFeatureArray {
…
NSMutableArray *returnArray = [NSMutableArray array];
…
return returnArray;
}
Also, unless it is relevant to callers that the array is mutable, you should change that method to return NSArray instead of NSMutableArray. You could keep your code as is, i.e., return a mutable array even though the method declaration states that the return type is NSArray.
As for your convenience constructor, there are essentially two choices depending on whether you want to return an owned or a non-owned object:
if you want to return an owned object, allocate it with +alloc or +new and return it without autoreleasing it. Your method name should contain new, e.g. +newFeatureWithId:…
if you want to return an object that’s not owned by the caller, allocate it with +alloc or new and autorelease it before/upon returning it to the caller. Your method name should not contain new, alloc, or copy.
In -setUpNavigationButtons, you obtain a non-owned array via +createFeatureArray, allocate a mutable array based on it, and release the mutable array without adding or removing elements from it. A mutable array makes sense when you need to add/remove elements. If you don’t have this need, you could change your method to:
- (void)setUpNavigationButtons {
// get array of features from feature data controller object
NSArray *featureArray = [FeatureController createFeatureArray];
…
// [featureArray release];
You’d remove that [featureArray release] since you do not own featureArray inside that method.
Edit: In -setUpNavigationButtons, you’re retaining the button you create and soon after you’re releasing it. In that particular method, those are idempotent operations — they aren’t wrong per se but are not necessary at all. You could replace that code with
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
…
[self.view addSubview:aButton];
// [aButton release];
i.e., do not retain it and do not release it.

UIView as dictionary key?

I want to have a NSDictionary that maps from UIViews to something else.
However, since UIViews do not implement the NSCopying protocol, I can't use them directly as dictionary keys.
You can use an NSValue holding the pointer to the UIView and use this as key. NSValues
are copyable. but, if the view is destroyed, the NSValue will hold a
junk pointer.
Here is the actual code (based on the answer by luvieere and further suggestion by Yar):
// create dictionary
NSMutableDictionary* dict = [NSMutableDictionary new];
// set value
UIView* view = [UILabel new];
dict[[NSValue valueWithNonretainedObject:view]] = #"foo";
// get value
NSString* foo = dict[[NSValue valueWithNonretainedObject:view]];
Although this isn't really what they're intended for, you could whip up a functional dictionary-like interface using Associative References:
static char associate_key;
void setValueForUIView(UIView * view, id val){
objc_setAssociatedObject(view, &associate_key, val, OBJC_ASSOCIATION_RETAIN);
}
id valueForUIView(UIView * view){
return objc_getAssociatedObject(view, &associate_key);
}
You could even wrap this up in a class ThingWhatActsLikeADictionaryButWithKeysThatArentCopyable*; in that case you might want to retain the views that you use as keys.
Something like this (untested):
#import "ThingWhatActsLikeADictionaryButWithKeysThatArentCopyable.h"
#import <objc/runtime.h>
static char associate_key;
#implementation ThingWhatActsLikeADictionaryButWithKeysThatArentCopyable
- (void)setObject: (id)obj forKey: (id)key
{
// Remove association and release key if obj is nil but something was
// previously set
if( !obj ){
if( [self objectForKey:key] ){
objc_setAssociatedObject(key, &associate_key, nil, OBJC_ASSOCIATION_RETAIN);
[key release];
}
return;
}
[key retain];
// retain/release for obj is handled by associated objects functions
objc_setAssociatedObject(key, &associate_key, obj, OBJC_ASSOCIATION_RETAIN);
}
- (id)objectForKey: (id)key
{
return objc_getAssociatedObject(key, &associate_key);
}
#end
*The name may need some work.
Provided you don't need to support before iOS 6, NSMapTable (suggested by neilsbot) works well because it can provide an enumerator over the keys in the collection. That's handy for code common to all of the text fields, like setting the delegate or bi-directionally syncing the text values with an NSUserDefaults instance.
in viewDidLoad
self.userDefFromTextField = [NSMapTable weakToStrongObjectsMapTable];
[self.userDefFromTextField setObject:#"fooUserDefKey" forKey:self.textFieldFoo];
[self.userDefFromTextField setObject:#"barUserDefKey" forKey:self.textFieldBar];
// skipped for clarity: more text fields
NSEnumerator *textFieldEnumerator = [self.userDefFromTextField keyEnumerator];
UITextField *textField;
while (textField = [textFieldEnumerator nextObject]) {
textField.delegate = self;
}
in viewWillAppear:
NSEnumerator *keyEnumerator = [self.userDefFromTextField keyEnumerator];
UITextField *textField;
while (textField = [keyEnumerator nextObject]) {
textField.text = [self.userDefaults stringForKey:[self.textFields objectForKey:textField]];
}
in textField:shouldChangeCharactersInRange:replacementString:
NSString *resultingText = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(resultingText.length == 0) return YES;
NSString *preferenceKey = [self.textFields objectForKey:textField];
if(preferenceKey) [self.userDefaults setString:resultingText forKey:preferenceKey];
return YES;
And now I will go cry, because I implemented all of this before realizing that my iOS 5.1-targeted app can't use it. NSMapTable was introduced in iOS 6.
Rather than store a pointer to the view and risk the garbage issue, just give the UIView a tag and store the tag's value in the dictionary. Much safer.
I'm using a simple solution under ARC provided by Objective-C++.
MyClass.mm:
#import <map>
#implementation MyClass
{
std::map<UIView* __weak, UIColor* __strong> viewMap;
}
- (void) someMethod
{
viewMap[self.someView] = [UIColor redColor];
}
In this example I am getting stronger type checking by making all the values have to be a UIColor* which is all I needed this for. But you could also use id as the value type if you want to allow any object as the value, ex: std::map<UIView* __weak, id __strong> viewMap; Likewise for keys: id __weak, id __strong> viewMap;
You can also vary the __strong and __weak attributes as needed. In my case, the views are already retained by the view controller that I use this in, so I saw no need to take a strong pointer to them.
a simple solution when you just want UIView as key occasionally,I use it to store UILabel and UIColor
NSArray<UIView *> *views = #[viewA,viewB,viewC,viewD];
NSArray *values = #[valueA,valueB,valueC,valueD];
for(int i = 0;i < 4;i++) {
UIView *key = views[i];
id value = values[i]
//do something
}
id value = values[[views indexOfObject:key]]

Unexpected Singleton class behavior on iPhone, am I doing something wrong?

I'm implementing a singleton class as follows:
static Singleton* _singletonInstance;
#implementation Singleton
+(void)initialize
{
_singletonInstance = [[Singleton alloc] init];
}
+(Singleton*)instance
{
return(_singletonInstance);
}
initialize only gets called the first time someone calls instance. I then have a method that I can call to set up some instance variables. So it ends up looking like this.
_singleton = [Singleton instance];
[_singleton setupWithParams: blah];
When i get an instance of this singleton inside an object, it works fine the first time; However, after i dealloc and create a new copy of the object that needs an instance of the singleton, i get a BAD ACCESS error when I try to call the setup function.
Just to test things I print out the address of the instance before I make the setup call and both times they report the same address, but when i check the error log for BAD ACCESS call, it lists a completely different memory address.
Does anyone have any ideas why this pointer to the instance seems to look fine when I print it, but when I make a call to it, it is seemingly pointing to random data?
The pointer value looks valid because it used to be, but most likely the memory has been free'd, which is why what it points to looks like random data.
You've acquired one reference with your [[Singleton alloc] init] above, but is there a release somewhere else that might be executing? I bet your code is calling instance, and then release-ing later, even though your code never acquired a reference. And that shouldn't be necessary for a singleton anyways. Just a guess...
Are you deallocing your _singletonInstance somewhere?
I'm using much more complex, but very stable version of Singleton template (taken with description from Brandon "Quazie" Kwaselow Blog):
static SampleSingleton *sharedSampleSingletonDelegate = nil;
+ (SampleSingleton *)sharedInstance {
#synchronized(self) {
if (sharedSampleSingletonDelegate == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedSampleSingletonDelegate;
}
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (sharedSampleSingletonDelegate == nil) {
sharedSampleSingletonDelegate = [super allocWithZone:zone];
// assignment and return on first allocation
return sharedSampleSingletonDelegate;
}
}
// on subsequent allocation attempts return nil
return nil;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
//do nothing
}
- (id)autorelease {
return self;
}
Valerii's code is better for implementing a singleton, but the problem is almost certainly that the code that calls [Singleton instance] is operating as if it has ownership without actually taking ownership using retain, and then is later releasing it.
Look there for your bug, and read the Memory Managment Rules.
Also, in Xcode, enable NSZombieEnabled and the console will show you when you try to message the object after its been released.

Possible View Caching problem?

I'm building an iphone app and I've got a table view with some textfields inside the cells, the content of the fields is set in viewWillAppear (its a grouped TableView w/ 3 fields that are always the same). The content of the text fields is retrieved from getter methods that return values from various class variables.
The problem I'm having is the getter seems to be returning the original value, not the value that is modified by the setter method. The class variable is an NSMutableString. Is it possible the view is caching the method call?
//header file
#implementation ManageWorkoutViewController : UIViewController {
NSMutableString *workoutDifficulty;
}
-(void)setWorkoutDifficulty:(NSString *)value;
-(NSString *)getWorkoutDifficulty;
#end
//implementation file
-(NSString *)getWorkoutDifficulty {
if (nil == workoutDifficulty) {
workoutDifficulty = [NSMutableString stringWithString:#"Easy"];
}
NSLog(#"getter: Returning workoutDifficulty as: %#", workoutDifficulty);
return workoutDifficulty;
} //end getWorkoutDifficulty
-(void)setWorkoutDifficulty:(NSString *)value {
workoutDifficulty = [NSString stringWithFormat:#"%d", value];
NSLog(#"setter: workoutDifficulty set as: %#", workoutDifficulty);
}//end setWorkoutDifficulty
//elsewhere in the implementation another table view is
//pushed onto the nav controller to allow the user to pick
//the difficulty. The initial value comes from the getter
workoutDifficultyController.title = #"Workout Difficulty";
[workoutDifficultyController setOriginalDifficulty:[self getWorkoutDifficulty]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[(UINavigationController *)self.parentViewController pushViewController:workoutDifficultyController
animated:YES];
//then in that workoutDifficultyController it calls back into the first controller to set the selected value:
[manageWorkoutController setWorkoutDifficulty:selectedDifficulty];
You've got many issues here. First, you're creating your accessors incorrectly. The problem that's particularly causing you trouble is this line:
workoutDifficulty = [NSString stringWithFormat:#"%d", value];
value is an NSString here. You should be receiving a warning about this. I believe "Typecheck Calls to printf/scanf" is turned on by default, and should catch this. workoutDifficulty is being set to some random number (probably taken from the first 4 bytes of value).
Here is what you probably meant. I would probably switch workoutDifficulty to an enum, but I'm keeping it an NSString for consistency with your code. I'm also doing this without properties because you did, but I would use a property here.
//header file
#implementation ManageWorkoutViewController : UIViewController {
NSString *_workoutDifficulty;
}
-(void)setWorkoutDifficulty:(NSString *)value;
-(NSString *)workoutDifficulty; // NOTE: Name change. "getWorkoutDifficulty" is incorrect.
#end
//implementation file
-(NSString *)workoutDifficulty {
if (nil == workoutDifficulty) {
_workoutDifficulty = [#"Easy" retain];
}
NSLog(#"getter: Returning workoutDifficulty as: %#", _workoutDifficulty);
return _workoutDifficulty;
} //end workoutDifficulty
-(void)setWorkoutDifficulty:(NSString *)value {
[value retain];
[_workoutDifficulty release];
_workoutDifficulty = value;
NSLog(#"setter: workoutDifficulty set as: %#", _workoutDifficulty);
}//end setWorkoutDifficulty
You have to retain workoutDifficulty whenever you set it to a new value (and release the old value).