当前位置:网站首页>【Objective-C】结构体和类的区别

【Objective-C】结构体和类的区别

2022-06-11 09:24:00 后端码匠

一、结构体只能封装属性,而类不仅可以封装属性还可以封装方法.

如果1个封装数据既有属性也有行为,只能用类.

二、结构体变量分配在栈.OC对象分配在堆.
栈的空间相对较小.但是存储在栈中的数据访问效率相对较高.
堆的空间相对较大.但是存储在堆中的数据的访问效率相对较低.

如果1个封装数据只有属性.如果用结构体就会分配在栈 效率就会高.
如果使用类型 对象就分配在堆 效率相对就会低.

如果定义1个结构体,这个结构体中有很多个属性.那么这个时候结构体变量在栈中就会占据很大1块空间 反而会降低效率.

什么时候使用结构体: 1. 封装数据只有属性 2. 属性较少(3个以下).

什么时候使用类: 1 .封装数据既有属性也有行为. 2 .只有属性 但是属性较多.

三、结构体赋值是 直接赋值的值. 而对象的指针 赋值的是对象的地址.

//
// StructPractice.h
// OneLiveIOS
//
// Created by Inke219223m on 2022/5/26.
//

#import <Foundation/Foundation.h>

struct Books {
    
   NSString *title;
   NSString *author;
   NSString *subject;
   int   book_id;
};

//位域
//位字段允许在结构中打包数据。当内存或数据存储非常宝贵时,这尤其有用。
//struct codingce_struct {
    
// unsigned int f1:1;
// unsigned int f2:1;
// unsigned int f3:1;
// unsigned int f4:1;
// unsigned int type:4;
// unsigned int my_int:9;
//} codingce;

//将多个对象打包成机器字。 例如 可以压缩1位标志。读取外部文件格式 - 可以读入非标准文件格式。9位整数。

struct codingce_struct {
    
   unsigned int f1:1;
   unsigned int f2:1;
   unsigned int f3:1;
   unsigned int f4:1;
   unsigned int type:4;
   unsigned int my_int:9;
};

NS_ASSUME_NONNULL_BEGIN

@interface StructPractice : NSObject


-(void) StructFunTest : (int) num1;


-(void) PrintStruct : (int) num1 : (struct Books) book;

@end

NS_ASSUME_NONNULL_END

//
// StructPractice.m
// OneLiveIOS
//
// Created by Inke219223m on 2022/5/26.
//

#import "StructPractice.h"

@implementation StructPractice
-(void) StructFunTest : (int) num1 {
    
    struct Books Book1; /* 声明Book类型变量:Book1 */
    struct Books Book2;
    Book1.title = @"我是幸运的";
    Book1.author = @"封神榜";
    Book1.subject = @"Objective-C编程教程";
    Book1.book_id = 81234566;
    
    Book2.title = @"Java";
    Book2.author = @"Maxsu";
    Book2.subject = @"C编程教程";
    Book2.book_id = 813283488;
    
    /* 打印 Book1 信息 */
    NSLog(@"Book 1 title : %@\n", Book1.title);
    NSLog(@"Book 1 author : %@\n", Book1.author);
    NSLog(@"Book 1 subject : %@\n", Book1.subject);
    NSLog(@"Book 1 book_id : %d\n", Book1.book_id);

    /* 打印 Book2 信息 */
    NSLog(@"Book 2 title : %@\n", Book2.title);
    NSLog(@"Book 2 author : %@\n", Book2.author);
    NSLog(@"Book 2 subject : %@\n", Book2.subject);
    NSLog(@"Book 2 book_id : %d\n", Book2.book_id);
    
    [self PrintStruct: 2 : Book1];
    
    struct Books *struct_pointer;
    struct_pointer = &Book1;
    
    NSLog(@"指向结构的指针:%@", struct_pointer->title);
       
}


-(void) PrintStruct : (int) num1 : (struct Books) book {
    
    NSLog(@"book title : %@\n", book.title);
    NSLog(@"book author : %@\n", book.author);
    NSLog(@"book subject : %@\n", book.subject);
    NSLog(@"book book_id : %d\n", book.book_id);
}
@end

原网站

版权声明
本文为[后端码匠]所创,转载请带上原文链接,感谢
https://codingce.blog.csdn.net/article/details/124993252