user1994291
user1994291

Reputation:

accessing objective c variable from c function

I have an objective c class that has a NSString object with property like that :

@property (nonatomic,retain) NSString *data;

now, from a c function , i want to do : data=@"abc"; , but the c function does not see data .

How would i access data from a pure c function in that same class ? I have tried with creating an object of that class within the c function but it crashes.

EDIT :

I have also tried to call obj c function with argument , i can call the function but without the argument : (in the C function )

     NSString *ran=@"";
    [refToSelf postNotification:ran];

do that without passing ran is working. how would i pass ran ??

Upvotes: 3

Views: 1306

Answers (1)

bbum
bbum

Reputation: 162722

If you have a C function in an Objective-C file, then the requirement is simple; you need a reference to the object you want to mess with.

void func(MyClass* anObj) {
    [anObj setData: @"foo"];
    anObj.data = @"foo"; // same as the line above
}

@interface MyClass:NSObject
@property(nonatomic,copy) NSString *data;
@implementation MyClass
- (void) callCFunc
{
     func(self);
     // the "data" property will now be set to @"foo"
}
@end

No more, no less. There is absolutely nothing different about calling a method in a C function than there is about calling a method of some other instance or class from a method. In fact, methods are nothing more than C functions with a default self and _cmd arguments.

It isn't clear what you are asking with your edit. If you "can't pass ran" then that implies that you are calling a method with no arguments:

- (void)postNotification;

If you want to pass ran, then you need a method that can consume the argument:

- (void)postNotification:(NSString*)data;

Upvotes: 15

Related Questions