简体   繁体   中英

get the value of a NSString variable

I have a weird problem. pictureLink is a global variable declared in .h

 NSString *pictureLink;
}
@property(retain,nonatomic) NSString *pictureLink;

i wrote this code

NSString * myPictureUrl=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
pictureLink=myPictureUrl;

I have a strange result, it must be a pointer Or

pictureLink=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];

i have EXC_BAD_ACESS error

It's memory management fault, you're not retaining myPictureUrl in your code.

[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash]; returns an autoreleased value, so you have two options:

  1. pictureLink=myPictureUrl; should look like [self setPictureLink:myPictureUrl]; .
  2. do a [myPictureUrl retain]; , and don't forget to release it later.

Consider using ARC (Automatic Retain Counting) for you project. With ARC the compiler takes care of retain counts so you don't have to, in fact aren't allowed to. There is a refactoring that will convert a current project.

You are bypassing your @property by calling directly the variable, so no magic provided by your @property settings is done, like retain and release.
you need to do self.pictureLink to use the @property .
To avoid the temptation of accessing directly my variable I do the following

NSString *theProperty
}
@property (nonatomic, retain) NSString *property;

and

@synthesise property = theProperty;

That way if I go around the @property I really, really wanted to do it.
But you need a very, very, very good reason to do so, and event then, it may not be a good enough reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM