类
定义类
OC:
// Cat.h
#import <Foundation/Foundation.h>
@interface Cat : NSObject
-(void)eat:(NSString*)food;
@end
// Cat.m
#import "Cat.h"
@implementation Cat
-(void)eat:(NSString*)food{
NSLog(@"%@, 好好吃!",food);
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "Cat.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
Cat * cat = [Cat new];
[cat eat:@"小鱼"];
}
}
ruby:
class Cat
def eat(food)
puts "#{food},好好吃!"
end
end
kitty = Cat.new
kitty.eat "小魚" #=> 小魚,好好吃!
初始化方法
OC:
...
- (instancetype)init
{
if(self = [super init])//说明父类的init方法执行成功
{
// 初始化子类自己的属性;
}
return self;
}!
...
ruby:
class Cat
def initialize(name, gender)
@name = name
@gender = gender
end
def say_hello
puts "hello, my name is #{@name}"
end
end
kitty = Cat.new("kitty", "female")
kitty.say_hello # => hello, my name is kitty
实例变量和属性
OC:
// Cat.h
#import <Foundation/Foundation.h>
@interface Cat : NSObject
@property(nonatomic, strong)NSString *name; // 属性
-(id)initWithName:(NSString*)name andGender:(NSString*)gender;
-(void)sayHello;
@end
// Cat.m
#import "Cat.h"
@interface Cat ()
{
NSString* _name; // 实例变量
NSString* _gender;
}
@end
@implementation Cat
-(id)initWithName:(NSString*)name andGender:(NSString*)gender{
if(self = [super init])
{
_name = name;
_gender = gender;
}
return self;
}
-(void)sayHello{
NSLog(@"hello, my name is %@", _name);
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "Cat.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
Cat * cat = [[Cat alloc]initWithName:@"kitty" andGender:@"female"];
[cat sayHello]; // => hello, my name is kitty
}
}
ruby:
class Cat
attr_accessor :name #属性
def initialize(name, gender)
@name = name # 实例变量
@gender = gender
end
def say_hello
puts "hello, my name is #{@name}" # => hello, my name is kitty
end
end
类方法和对象方法
OC:
// Cat.m
#import "Cat.h"
@interface Cat ()
@end
@implementation Cat
+(void)info{
// 类方法
}
-(void)sayHello{
// 对象方法
}
@end
ruby:
class Cat
# 类方法
def self.info
# ...
end
# 对象方法
def say_hello
# ...
end
end
模块
OC:
// NSObject+Flyable.h
#import <Foundation/Foundation.h>
@interface NSObject (Flyable)
-(void)fly;
@end
// NSObject+Flyable.m
#import "NSObject+Flyable.h"
@implementation NSObject (Flyable)
-(void)fly{
NSLog(@"I can fly!");
}
@end
// Cat.h
#import <Foundation/Foundation.h>
#import "NSObject+Flyable.h"
@interface Cat : NSObject
@end
// Cat.m
#import "Cat.h"
@implementation Cat
@end
// main.m
#import <Foundation/Foundation.h>
#import "Cat.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
Cat * cat = [Cat new];
[cat fly]; // => I can fly!
}
}
ruby:
module Flyable
def fly
puts "I can fly!"
end
end
class Cat
include Flyable
end
kitty = Cat.new
kitty.fly # => I can fly!
参考资料:
railsbook
- 持续更新。
- 若有更好的资料,感谢交流。
- 若有错误的内容,感谢斧正。
网友评论