Accessing member variables from another thread crashes
Accessing member variables from another thread crashes
- Subject: Accessing member variables from another thread crashes
- From: "Dennis Harms" <email@hidden>
- Date: Sun, 10 Aug 2008 02:24:44 +0200
I'm new to Cocoa and objective C development and I've got a big problem with
multithreading:
I've created a class with some member variables of type NSString*. In the
init function of the class, I write something into those strings. Now I call
a function of the initialized class instance as a new thread and try to read
from those member variables. This leads to a crash... Can someone give me a
hint as to why this won't work?
Here's my code, shrunk down to just the problematic part:
---------- MyClass.h -----------------------------
@interface MyClass: NSObject
{
@private
NSString* baseURL;
}
- (id) initWithHost: (NSString*) _url;
- (void) doSomething: (id) object;
@end
----------------------------------------------------------
---------- MyClass.m -----------------------------
@implementation MyClass
- (id) initWithHost: (NSString*) _url
{
self = [super init];
baseURL = [NSString stringWithString: _url];
return self;
}
- (void) doSomething: (id) object
{
NSString *url = [NSString stringWithString: baseURL]; // <-- the crash
occurs even when just reading the member
}
@end
----------------------------------------------------------
I've tried calling the function in the same thread, as well as three
different ways of calling it in a seperate thread. Every time there's
another thread involved, it crashes when accessing the member variable. If
the function doesn't access any members, the code works just fine...
instance = [[MyClass alloc] initWithHost: txtHost.text];
[instance doSomething: nil]; // Works
[instance performSelectorInBackground: @selector(doSomething:) withObject:
nil]; // Doesn't work
[[[NSThread alloc] initWithTarget: instance selector:
@selector(doSomething:) object: nil] start]; // Doesn't work
[NSThread detachNewThreadSelector: @selector(doSomething:) toTarget:
instance withObject: nil]; // Doesn't work
Thanks,
Dennis
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden