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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to