0

I want to do the following

+(void)DoThis
{
    [textView setString:@"qwertyasdfzxcvb."];
    [textView setNeedsDisplay:YES];
}

However, It refuses to set the string. Because this works,

-(void)DoThis
{
    [textView setString:@"qwertyasdfzxcvb."];
    [textView setNeedsDisplay:YES];
}

I come to the conclusion that the string refuses to be set in a method with class level access. So how do I allow a string to be set from a +(void)?

evdude100
  • 437
  • 4
  • 18

4 Answers4

2

Assuming textView is an instance variable, there is no way to access it. At best, you can

+ (void)DoThis:(UITextView*)aTextView {
    [aTextView setString:@"qwertyasdfzxcvb."];
    [aTextView setNeedsDisplay:YES];
}
Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
2

What you are most likely trying to do is set an instance variable from a class method. This does not work because class objects are not instances of the class and therefore cannot access instance variables. So your method + (void)DoThis does not have access to the textView instance variable because the class object is not an instance of the class.

EJV
  • 1,009
  • 1
  • 10
  • 17
2

You can not set an instance variable from a class method. If you want to declare a "class variable" you have to make a static global variable inside the .m file of the class because there are no class variables in Objective-C. This is a C static variable, not in the sense Java or C# consider it. Here, "static" ensures that the variable can not be used outside of that file.

Community
  • 1
  • 1
albertamg
  • 28,492
  • 6
  • 64
  • 71
1

I think what you may be looking for is the singleton/shared pattern, which allows any code to access a particular instance of a class without being passed that instance.

This model is used throughout Cocoa. For example, NSFileManager has a class method defaultManager which returns the shared instance of the class. You call an instance method on this shared instance by first invoking defaultManager, so for example to call the instance method isDeletableFileAtPath you write:

[[NSFileManager defaultManager] isDeletableFileAtPath:path]

In your case your DoThis becomes:

+ (void) DoThis
{
    EvDudeClass *shared = [EvDudeClass sharedInstance];
    [shared.textView setString:@"qwertyasdfzxcvb."];
    [shared.textView setNeedsDisplay:YES];
}

And you need to add a sharedInstance method to your class. There a number of ways to do this depending on how you wish to use your class - Is it a singleton? Do you just need one shared instance and other non-shared ones? Do you just want to share the instance created in the NIB? As you mention IBOutlet here is an implementation which does the latter:

static EvDudeClass *privateSharedInstance = nil;

- (void) awakeFromNib
{
    privateSharedInstance = self; // save this instance so it can be shared
    // other init stuff
}

+ (EvDueClass *)sharedInstance { return privateSharedInstance; }
CRD
  • 52,522
  • 5
  • 70
  • 86