標籤: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-C----執行個體變數