标签:objective 实例 oc objective-c 实例变量
OC中的?方法分两种:类?方法和实例?方法。
类?方法:只能类使?用,例如:+(id)alloc 注:类?方法中不能使?用 实例变量
实例?方法:只能对象使?用,例如: -(void)sayHi
//
// main.m
// OC_Practice_02
//
// Created by on 15/3/31.
// Copyright (c) 2015年 . All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
#import "AudiCar.h"
#import "Car.h"
#import "Engine.h"
#import "Tire.h"
int main(int argc, const char * argv[]) {
Person *aPerson = [[Person alloc] init] ;
//为其相关属性赋值
aPerson->_address = @"郑州市高新区莲花池水沟子" ;
aPerson->_hobby = @"敲代码" ;
//一个类中赋值和取值方法的定义是为了解决受保护的和私有的实例变量无法直接通过对象加指向操作符来访问的形式。属于间接访问。
// [aPerson setName:@"河南省"] ;
// [aPerson setAge:12] ;
// [aPerson setSex:@"女"] ;
[aPerson setName:@"ha"
age:23
sex:@"hei"] ;
NSLog( @"\n%@, %d, %@",
[aPerson getName],
[aPerson getAge],
[aPerson getSex] ) ;
//自定义初始化方法是在创建对象时对对应的实例变量做赋值操作,而setter方法是在创建对象之后对对应的实例变量做赋值操作,两种都可以完成赋值,但是赋值的时机不同。
//初始化方法只能在创建对象时被调用一次,而赋值方法可以根据项目需要的具体需求被多次调用。
Person *anotherPerson = [[Person alloc] initWithName:@"heihei"
age:45
sex:@"nv"] ;
NSLog(@"\nname:%@, age:%d, sex:%@",
[anotherPerson getName],
[anotherPerson getAge],
[anotherPerson getSex] ) ;
Person *fivePerson = [[Person alloc] initWithName:@"en"
age:23
sex:@"en"
address:@"ehh"
hobby:@"hen"] ;
NSLog(@"\nname:%@, age:%d, sex:%@, address:%@, hobby:%@",
[fivePerson getName],
[fivePerson getAge],
[fivePerson getSex],
fivePerson->_address,
fivePerson->_hobby ) ;
AudiCar *oneCar = [[AudiCar alloc] initWithColor:@"ee"
price:1.3
horsePower:2.2
type:@"ee"] ;
NSLog(@"color:%@, price:%.2f, horsePower:%.2f, type:%@",
oneCar->_color,
oneCar->_price,
oneCar->_horsePower,
oneCar->_type ) ;
//创建引擎对象
Engine *anEngine = [[Engine alloc] initWithBrand:@"V8"
horsePower:2000] ;
Car *aCar = [[Car alloc] init] ;
//为当前的汽车对象安装引擎
[aCar setEngine:anEngine] ;
for (int i = 0; i < 4; i++ ) {
Tire *aTire = [[Tire alloc] initWithBrand:@"米其林"
size:29] ;
[aCar setTire:aTire atIndex:i] ;
}
[aCar run];
return 0;
}
标签:objective 实例 oc objective-c 实例变量
原文地址:http://blog.csdn.net/zhengang007/article/details/46548529