用C語言封裝OC對象(耐心閱讀,非常重要)


本文的主要內容來自這里

前言

做iOS開發的朋友,對OC肯定非常了解,那么大家有沒有想過OC中NSInteger,NSObject,NSString這些對象是怎么封裝的?接下來我們就使用C語言來一部一部的實現這個封裝。

Object對象

首先我們先封裝一個Object對象,我們來分析一下:

  • 如果使用C來封裝對象,我們就要用到結構體
  • 每一個Object都有一個計數器,這個計數器用來管理對象的釋放
  • 提供一定的方法,能夠retain, release, 獲取計數器個數

好了,基於上邊的設計呢,我們寫了如下的代碼:

Object.h

#include "Object.h"

// 定義Object對象
typedef struct Object {
    int retainCount;
}Object;

//宏定義方法 方便書寫
#define OBJECTRETAIN(obj) objectRetain((Object*)obj)
#define OBJECTRELEASE(obj) objectRelease((Object*)obj)
#define GETRETAINCOUNT(obj) getRetainCount((Object*)obj)
void objectRetain(Object *obj);
void objectRelease(Object *obj);
int getRetainCount(Object *obj);

接下來,我們只要在.c中實現這三個方法就行了。

Object.c

#include "Object.h"
#include <stdlib.h>

void objectRetain(Object *obj) {
    obj -> retainCount += 1;
}

void objectRelease(Object *obj) {
    obj -> retainCount -= 1;
    if (obj -> retainCount <= 0) {
        free(obj);
    }
}

int getRetainCount(Object *obj) {
    return obj -> retainCount;
}

String對象

我們使用C語言的char *來封裝String對象:

String.h

#ifndef String_h
#define String_h

#include <stdio.h>

typedef struct String {
    int retainCount;
    char *value;
}String;

String* newString(char* value);
char* getStringValue(String* ins);


#endif /* String_h */

String.c

#include "String.h"
#include <stdlib.h>
#include "Object.h"

String* newString(char* value) {
    String *str = malloc(sizeof(String));
    objectRetain((Object *)str);
    str -> value = value;
    return str;
}

char* getStringValue(String* ins) {
    return ins -> value;
}

Integer對象

Integer是對Int的封裝。

Integer.h

#ifndef Integer_h
#define Integer_h

#include <stdio.h>

typedef struct Integer{
    int retainCount;
    int value;
    
}Integer;

Integer* newInteger(int value);
int getIntegerValue(Integer* ins);
#endif /* Integer_h */

Integer.c

#include "Integer.h"
#include <stdlib.h>
#include "Object.h"

Integer *newInteger(int value) {
    Integer *new = malloc(sizeof(Integer));
    OBJECTRETAIN(new);
    new->value = value;
    return new;
}

int getIntegerValue(Integer* ins) {
    return ins->value;
}

People對象

People對象中有兩個屬性,一個是String類型的姓名,一個是Integer類型的年齡,原理和上邊的封裝非常相似。

People.h

#ifndef People_h
#define People_h

#include <stdio.h>
#include "Integer.h"
#include "String.h"

typedef struct People{
    int retainCount;
    String* name;
    Integer* age;
    
}People;

People* newPeople(String *name,Integer *age);
String* getName(People* people);
Integer* getAge(People* people);
#endif /* People_h */

People.c

#include "People.h"
#include <stdlib.h>
#include "Object.h"

People* newPeople(String *name,Integer *age){
    People *newP = malloc(sizeof(People));
    OBJECTRETAIN(newP);
    newP->age = age;
    newP->name = name;
    return newP;
}
String* getName(People* people){
    return people->name;
}
Integer* getAge(People* people){
    return people->age;
}

Array對象

我們上邊定義了好幾個對象,接下來我們在定義一個數組對象,我們最終的目的是,實現類似OCNSArray的一些簡單的功能,這這里我們會把People放入數組中。

  • 數組需要一個參數length,用來獲取數組中的元素個數
  • 還需要一個參數capacity,用來說明數組的容量
  • AnyObject *value,數組中放着的是一組連續內存的Object對象

代碼分析:

//創建數組
Array* newArray(){
    Array *arr = malloc(sizeof(Array));
    arr->length = 0;
    arr->capacity = 32;
    arr->value = allocMemoryByCapacity(arr);
    return arr;
}

//分配空間
static AnyObject* allocMemoryByCapacity(Array *arr){
    return malloc(sizeof(People*) * arr->capacity);
}

AnyObject是一個對象,他封裝了Object *。malloc函數分配了一段內存后,返回了指向這段內存的指針,也就是AnyObject*.

在創建Array的時候,value就可以直接使用這個指針進行賦值,同C中的數組是一個概念。

Array.h

#ifndef Array_h
#define Array_h

#include <stdio.h>
#include "People.h"
#include "Object.h"
typedef Object* AnyObject;

typedef struct Array{
    int length;
    int capacity;
    AnyObject *value;
    
}Array;

Array* newArray();

//增加數組元素
void addElement(Array *array,AnyObject value);

//刪除
Array* removeIndexAt(Array *arry,int index);

//插入
Array* insertIndexAt(Array *array,AnyObject value,int index);

//查找
AnyObject getValueIndexAt(Array *array,int index);

//獲取數組長度
int getArrayLength(Array *array);

//銷毀
void destroyArray(Array *array);

//打印
void printArray(Array *arr);

#endif /* Array_h */

Array.c

#include "Array.h"
#include <String.h>
#include <stdlib.h>
#include <assert.h>


//分配空間
static AnyObject* allocMemoryByCapacity(Array *arr){
    return malloc(sizeof(People*) * arr->capacity);
}

//創建數組
Array* newArray(){
    Array *arr = malloc(sizeof(Array));
    arr->length = 0;
    arr->capacity = 32;
    arr->value = allocMemoryByCapacity(arr);
    return arr;
}

//獲取數組長度
int getArrayLength(Array *array){
    return array->length;
}

//增加元素
void addElement(Array *array,AnyObject value){
    if (array->length >= array->capacity) {
        array->capacity *= 2;
        AnyObject *oldValue = array->value;
        memcpy(array->value, oldValue, array->length*sizeof(AnyObject));
        free(oldValue);
    }
    OBJECTRETAIN(value);
    array->value[array->length] = value;
    array->length++;
}

//刪除元素
Array* removeIndexAt(Array *arry,int index){
    assert(index >= 0 && index < arry->length);  //斷言 防止越界
    
    OBJECTRELEASE(getValueIndexAt(arry, index));
    
    arry->length -- ;
    for (int i = index; i < arry->length; i++) {
        arry->value[i] = arry->value[i+1];
    }
    return arry;
}

//在指定位置增加元素
Array* insertIndexAt(Array *array,AnyObject value,int index){
    if (array->length >= array->capacity) {
        array->capacity *= 2;
        AnyObject *oldValue = array->value;
        memcpy(array->value, oldValue, array->length*sizeof(AnyObject));
        free(oldValue);
    }
    array->length++;
    
    for (int i = 1; i <= array->length - index; i++) {
        array->value[array->length - i] = array->value[array->length- i - 1];
    }
//    //將元素后移
//    for (int i = 0; i < array->length - index; i++) {
//        array->value[array->length - 1] = array->value[array->length - 1 - 1];
//    }
    //插入指定位置
    array->value[index] = value;
    OBJECTRETAIN(value);
    return array;
}



//獲取某個元素
AnyObject getValueIndexAt(Array *array,int index){
    assert(index >= 0 && index < array->length);
    return array->value[index];
}

//銷毀
void destroyArray(Array *array){
    free(array->value);
    free(array);
    printf("數組被銷毀\n");
}
//打印結果
void printArray(Array *arr){
    for (int i = 0; i < arr->length; i++) {
        printf("位置:%d,姓名:%s,年齡:%d\n",i, getStringValue(getName((People*)getValueIndexAt(arr, i))),getIntegerValue(getAge((People*)getValueIndexAt(arr, i))));
    }
}

測試

在這里下載源碼https://github.com/agelessman/MCC-2-OC-Object.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM