03.OC对象操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oXinYangonly/article/details/80800538

字符串的声明

在OC中,用NSString类声明的字符串时一个对象

  • @创建字符串
NSString * str = @"hello string";
  • 创建一个格式化的字符串
NSString * formatStr = [NSString stringWithFormat:@"name=%s,age=%d","zhangsan",10];

字符串输出

NSLog(@"%@",str);

字符串的操作介绍

  • 计算字符串的长度
NSUInteger len = [str length];

length方法计算的是个数

结构体作为对象属性

  • 声明和实现
#import <Foundation/Foundation.h>

typedef struct{
    int year;
    int month;
    int day;
} Date;

@interface User : NSObject
{
    @public
    NSString * _name;
    Date _birthday;
}

- (void) say;
@end

@implementation User

- (void) say{
    NSLog(@"name=%@,year=%i,month=%i,day=%i",_name,_birthday.year,_birthday.month,_birthday.day);
}

@end
  • 调用

首先创建对象

User * user = [User new];

我们在对结构体属性进行赋值时,要注意,不能使用下面的方式

user->_birthday = {1999,1,1};

user->_birthday = {1999,1,1};这种方式是错误的,因为系统在赋值时,无法判断{1999,1,1}是数组还是结构体

对结构体属性进行赋值,有三种方式

  1. 强制类型转换
user->_birthday = (Date){1999,1,1};
  1. 先创建一个结构体变量,然后将这个变量赋值给该属性
Date d ={1999,1,1};
user->_birthday = d;
  1. 对结构体中的每一个变量分别进行赋值
user->_birthday.year = 1999;
user->_birthday.month = 1;
user->_birthday.day = 1;

将对象作为方法的参数

@interface Gun : NSObject

- (void)shoot;
@end

@implementation Gun

- (void)shoot{
    NSLog(@"shoot");
}

@end


@interface Soldider : NSObject

- (void)fire:(Gun *)gun;
@end

@implementation Soldider

- (void)fire:(Gun *)gun{
    [gun shoot];
}

@end

//主函数
int main(int argc, const char * argv[]) {
    Soldider *s = [Soldider new];

    Gun *g = [Gun new];
    [s fire:g];
    return 0;
}

猜你喜欢

转载自blog.csdn.net/oXinYangonly/article/details/80800538