Skip to content

Instantly share code, notes, and snippets.

@prespondek
Last active August 29, 2015 14:13
Show Gist options
  • Save prespondek/4713365e8dd98d720995 to your computer and use it in GitHub Desktop.
Save prespondek/4713365e8dd98d720995 to your computer and use it in GitHub Desktop.
Objective C Demo
/****** ObjC.h ******/
#import <somelib.h>
@class MyClass; // forward declaration
// a protocol is similar to an abstract class in C++
@protocol MyProtocol
- (BOOL) protocolFunction;
@end
// Objective C does not have templates. The class between the arrows below just declares what protocol it impliments.
// Note that an object can inhereit only one base class but multiple protocols.
// NSObject is the base class of all objects in objective c
@interface MyClass : NSObject<MyProtocol> {
int _protected_value; // member values are protected by default
void(^_callback)(float val); // function pointer.
@public
int _public_value; // public variable
}
// properties are variables that automatically create getters and setters for you. You can override them if needed.
// options between in brackets here define behaviour of the property.
// For instance, nonatomic means the property can be accessed by multiple threads are the same time.
@property (nonatomic, readonly) NSString* PropertyString;
+ (MyClass *)sharedInstance; // static function.
- (instancetype)init; // constructor
- (void)dealloc; // destructor
- (void)classFunction:(NSString*)name callback:(void(^)(float))callback;
@end
/****** ObjC.m ******/
static MyClass* instance = nil;
@implementation MyClass
// you can change the internal variable name of properties using synthesize.
// By default all properties get an underscore at the start of their name.
@synthesize PropertyString = _property_string;
+ (MyClass*)sharedInstance
{
if (instance == nil) {
instance = [[self alloc] init];
}
return instance;
}
// constructor
- (instancetype)init
{
self = [super init];
if (self) {
_protected_value = 1;
_public_value = 2;
}
return self;
}
// destructor
- (void) dealloc
{
}
- (void)classFunction:(NSString*)name callback:(void(^)(float))callback
{
_callback = callback;
}
- (BOOL) protocolFunction
{
BOOL val = TRUE;
return val;
}
@end
/****** main.m ******/
int main(int argc, const char * argv[])
{
MyClass* test = [MyClass sharedInstance];
NSString* str = @"some text";
[test classFunction:str callback:^(float aFloat) { //lambda function
// do something
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment