本文的主要内容来自这里

前言

做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

用C语言封装OC对象(耐心阅读,非常重要)的更多相关文章

  1. OC对象,自动释放池,OC与C语言的区别

    在C语言中,编程都是面向过程的编程,每一个代码块都严格按照从上至下的顺序执行,在代码块之间同样也是这样, 但是在OC中往往不是这样,OC和C++.java等语言一样,都是面向对象的编程语言,在代码的执 ...

  2. IOS基础之 (四) OC对象

    一 建立一个OC的类 完整的写一个函数:需要函数的声明和定义. 完整的写一个类:需要类的声明和实现. 1.类的声明 声明对象的属性和行为 #import <Foundation/Foundati ...

  3. oc是一个全动态语言,oc的一切都是基于runtime实现的!

    oc是一个全动态语言,oc的一切都是基于runtime实现的! 从以下三方面来理解runtime吧! 1. 传统的面向过程的语言开发,例如c语言.实现c语言编译器很简单,只要按照语法规则实现一个LAL ...

  4. 【OC底层】OC对象本质,如 isa, super-class

    Objective-C的本质 1.我们编写的Objective-C,底层现实都是C/C++,代码生成步骤如下:   2.在OC中的所有面向对象的实现,都是基于C/C++的数据结构实现的 3.将Obje ...

  5. OC对象的本质及分类

    Object-C的底层都是通过C/C++来实现的,所以OC中的对象也会转化成C/C++中的某一个数据结构, 我们在终端里通过指令 xcrun -sdk iphoneos clang -arch arm ...

  6. R语言封装函数

    R语言封装函数 原帖见豆瓣:https://www.douban.com/note/279077707/ 一个完整的R函数,需要包括函数名称,函数声明,函数参数以及函数体几部分. 1. 函数名称,即要 ...

  7. ARC下OC对象和CF对象之间的桥接(bridge)

    在开发iOS应用程序时我们有时会用到Core Foundation对象简称CF,例如Core Graphics.Core Text,并且我们可能需要将CF对象和OC对象进行互相转化,我们知道,ARC环 ...

  8. hibernate将本地SQL查询结果封装成对象

    hibernate将本地SQL查询结果封装成对象 不知道大家有没有碰过这种情况,迫于很多情况只能用native SQL来查询(如:复杂统计等),然而使用native查询后,结果会被放到object里, ...

  9. OC 对象和匿名对象

    OC 对象和匿名对象 对象和匿名对象的定义: 当new出一个对象时,如果用一个指针接收这个对象,那么这个指针通常被称为对象. 如果new出的对象,不用指针接收,那么这个对象就称为匿名对象. #impo ...

随机推荐

  1. 在Openfire上弄一个简单的推送系统

    推送系统 说是推送系统有点大,其实就是一个消息广播功能吧.作用其实也就是由服务端接收到消息然后推送到订阅的客户端. 思路 对于推送最关键的是服务端向客户端发送数据,客户端向服务端订阅自己想要的消息.这 ...

  2. setTimeout 的黑魔法

    setTimeout,前端工程师必定会打交道的一个函数.它看上去非常的简单,朴实.有着一个很不平凡的名字--定时器.让年少的我天真的以为自己可以操纵未来.却不知朴实之中隐含着惊天大密.我还记得我第一次 ...

  3. console的高级使用

    1.console.table()用来表格化展示数据. var people = { zqz: { name: 'zhaoqize', age: 'guess?' }, wdx: { name: 'w ...

  4. Redis/HBase/Tair比较

    KV系统对比表 对比维度 Redis Redis Cluster Medis Hbase Tair 访问模式    支持Value大小 理论上不超过1GB(建议不超过1MB) 理论上可配置(默认配置1 ...

  5. 一道返回num值的小题目

    题目描述: 实现fizzBuzz函数,参数num与返回值的关系如下: .如果num能同时被3和5整除,返回字符串fizzbuzz .如果num能被3整除,返回字符串fizz .如果num能被5整除,返 ...

  6. [.NET] C# 知识回顾 - 委托 delegate (续)

    C# 知识回顾 - 委托 delegate (续) [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6046171.html 序 上篇<C# 知识回 ...

  7. STM32F429 LCD程序移植

    STM32F429自带LCD驱动器,这一具有功能给我等纠结于屏幕驱动的程序员带来了很大的福音.有经验的读者一定有过这样的经历,用FSMC驱动带由控制器的屏幕时候,一旦驱动芯片更换,则需要重新针对此驱动 ...

  8. c# Enumerable中Aggregate和Join的使用

    参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/asp.net-core-environment.html http://www.yuanjiaochen ...

  9. VS2015常用快捷键总结

    生成解决方案 F6,生成项目Shift+F6 调试执行F5,终止调试执行Shift+F5 执行调试Ctrl+F5 查找下一个F3,查找上一个Shift+F3 附加到进程Ctrl+Alt+P,逐过程F1 ...

  10. LINQ to SQL Where条件

    1. 适用场景 实现条件的过滤和查询等功能. 2. 说明 跟SQL语句中的where作用相似,都起到了范围的限定即过滤的作用,而判断条件是紧跟后面的条件子句.where主要分为三种形式:简单形式.条件 ...