Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Declaration Error - please explain

@interface Connections()
{
   static Connections *this;
}
@end

The above piece of code in .m file throwing compiler error

Type name does not allow storage class to be specified

at the same time when the

static

key word is removed it works well - which so obvious. Purpose : I want "Connections" instance static and private.

Why is this behavior, please help.

like image 713
Futur Avatar asked Feb 19 '13 14:02

Futur


People also ask

What does @() mean in Objective-C?

In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals. '@' is used a lot in the objective-C world.

Why does Objective-C use yes and no?

It's just syntax, there's no technical reason for it. They just use YES/NO for their BOOL instead of true/false like c++ does.

What is Objective-C category?

In order add such extension to existing classes, Objective-C provides categories and extensions. If you need to add a method to an existing class, perhaps, to add functionality to make it easier to do something in your own application, the easiest way is to use a category.


1 Answers

You cannot declare class-level variables in Objective-C classes; instead you need to "hide" them in the implementation file, often giving them static-scope so they cannot be accessed externally.

Connections.m:

#import "Connections.h"

static Connections *_sharedInstance = nil;

@implementation Connections

...

@end

And if this is a singleton, you typically define a class-level accessor to create the singleton upon first use:

+ (Connections *)sharedInstance
{
    if (_sharedInstance == nil)
    {
        _sharedInstance = [[Connections alloc] init];
    }
    return _sharedInstance;
}

(and you'll need to add the declaration in the .h file):

+ (Connections *)sharedInstance;
like image 195
trojanfoe Avatar answered Sep 21 '22 16:09

trojanfoe