开发者

IPhone - Objective C - How to share external variables in multiple threads?

In an IPhone app I made a constants file to hold my global variables:

MyConstants.h
extern NSMutableString * MY_GATEWAY;


MyConstants.m
NSMutableString * MY_GATEWAY;

In my app delegate I have imported MyConstants.h, and can successfully append to MY_GATEWAY and initialize my global variable with a url like this:

 MY_GATEWAY = [NSMutableString stringWithString:MY_PROTOCOL];
[MY_GATEWAY appendString:MY_HOST];

From my app delegate, after initializing MY_GATEWAY, I launch a new thread. 开发者_开发百科My thread class also imports MyConstants.h and in the main loop of that thread I try to read MY_GATEWAY but the value is garbage:

2011-08-13 22:23:47.246 MyProject[930:5c03] da.lproj

Should I be able to read this variable from a secondary thread? If so, am I doing something wrong?


Your mistake is actually a classic memory allocation error. This:

MY_GATEWAY = [NSMutableString stringWithString:MY_PROTOCOL];

Creates an autoreleased string and sets MY_GATEWAY to point to it. You don't actually own the string, all you're guaranteed is that it'll last at least as long as the call stack. So autoreleased objects are typically used to return results from functions or to create temporary objects without having explicitly to worry about ownership.

By the time your second thread gets around to accessing MY_GATEWAY, the original string has been deallocated and just by coincidence some other object has been put at the same address.

What you want to do is:

MY_GATEWAY = [[NSMutableString alloc] initWithString:MY_PROTOCOL];

Any call with new, alloc, retain or create in the name gives you an owning reference. When you have an owning reference, you know for certain that the object will hang around until you explicitly release it.

The official guide to the rules governing memory management is here. This blog post is also quite useful.

If you're not into worrying about memory management, Apple have announced that the version of the tools for iOS 5 will be able to handle most of these issues for you. The specifics are under NDA but if you sign in to Apple's developer site with your developer programme account then you can get betas of the next releases of the tools and relevant documentation. Look out for references to Automatic Reference Counting (or ARC).


Do

MY_GATEWAY = [[NSMutableString stringWithString:MY_PROTOCOL] retain];

Otherwise your MY_GATEWAY string gets autoreleased.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜