---
title: "MacOS 编程"
author: "lobin"
date: "2022-03-15T20:05:01Z"
tags: []
categories: ["编程语言"]
slug: "macos"
draft: false
lastmod: "2022-08-17T23:13:40Z"
id: 2524597
url: "https://lobin.iteye.com/blog/2524597"
---

# MacOS 编程

- ### MacOS 编程：框架 [https://lobin.iteye.com/admin/blogs/2524523](/admin/blogs/2524523 "https://lobin.iteye.com/admin/blogs/2524523")

MacOS主流编程语言主要是Objective-C/C++以及Swift，MacOS上的框架也都是采用这两种语言编写。在MacOS上编写程序基本也离不开这两种语言，当然，Objective-C/C++也可以混合C/C++编写程序，也可以直接使用C/C++来编写程序。

 

MacOS主流开发环境为XCode。

写道

XCode  
https://lobin.iteye.com/admin/blogs/2524634

 

当然也可以自行构造XCode工程，甚至也可以直接使用命令去构建整个工程。

 

$ otool -L /usr/lib/libc.dylib

 

main

 

NSApplicationMain

 

NSApplicationMain(), which is functionally similar to the following:

```
void NSApplicationMain(int argc, char *argv[]) {
    [NSApplication sharedApplication];
    [NSBundle loadNibNamed:@"myMain" owner:NSApp];
    [NSApp run];
}
```

 

 

写道

Overview of the Mach-O Executable Format  
https://developer.apple.com/library/archive/documentation/Performance/Conceptual/CodeFootprint/Articles/MachOOverview.html

 

写道

Mach-O Programming Topics  
https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/MachOTopics/0-Introduction/introduction.html

 

# 窗口

MacOS开发GUI可以使用Cocoa或者直接使用AppKit。

# 窗口样式

由NSWindowStyleMask定义

```
typedef NS_OPTIONS(NSUInteger, NSWindowStyleMask) {
  ...
};
```

NSWindowStyleMaskBorderless

NSWindowStyleMaskTitled

NSWindowStyleMaskClosable

NSWindowStyleMaskMiniaturizable

NSWindowStyleMaskResizable

NSWindowStyleMaskTexturedBackground

NSWindowStyleMaskUnifiedTitleAndToolbar

NSWindowStyleMaskFullScreen

NSWindowStyleMaskFullSizeContentView

NSWindowStyleMaskUtilityWindow

NSWindowStyleMaskDocModalWindow

NSWindowStyleMaskNonactivatingPanel

NSWindowStyleMaskHUDWindow

 

 

 

 

# 网络编程

MacOS编写网络程序可以通过CoreFoundation框架提供的CFSocket或者CFStream。也可以通过Foundation框架提供的NSStream。

 

# IOS

IOS下编写app的话，很多编程框架和MacOS差不多，除了编写图形化界面部分，IOS下有UIKit，对应MacOS下的AppKit。 UIKit和AppKit其实也差不多，很多界面UI组件都类似，基本可以一一对应。

 

# UIKit

 

 

# UIKit和AppKit的区别

AppKit是MacOS开发图形化用户界面程序的框架，对之对应，UIKit是IOS下app开发的框架。这两个框架非常相似，提供的开发界面UI组件也基本相似，很多都有对应的UI组件，如AppKit的NSView和UIKit的UIView。AppKit中的UI组件基本都以NS\*开头，对应UIKit框架，UI组件基本都以UI\*开头。

# UIView

 

# UIWindow

 

UIWindow和AppKit中对应的NSWindow不同，UIWindow并不是NSWindow那种表示一个窗口。在IOS下不像MacOS下有窗口这种概念。

 

# UITextField

 

 

 

# UITextView

 

 

 

# UIButton

 

 

# UITableView

 

 

 

# UIScrollView

 

 

 

 

# UITabBar

```
UITabBar *mainTabBar = [[UITabBar alloc] init];
[mainTabBar setDelegate: self];
[mainTabBar setBackgroundColor:backgroundColor];
```

添加选项卡

调用items的setter方法setItems添加选项卡。选项卡由UITabBarItem定义。

 

也可以调用setItems:animated:方法，这个方法多了一个animated参数，

\- (void)setItems:(nullableNSArray&lt;UITabBarItem \*&gt; \*)items animated:(BOOL)animated;

# UITabBarDelegate

 

 

UITabBar除了可以直接创建，还可以通过MVC方式，即通过UITabBarController。

 

如果指定了delegate，在选择一个选项卡时，会触发调用UITabBarControllerDelegate的tabBarController:shouldSelectViewController:方法。

 

\- (BOOL)tabBarController:(UITabBarController \*)tabBarController shouldSelectViewController:(UIViewController \*)viewController NS\_AVAILABLE\_IOS(3\_0);

 

 

 

 

 

 

 

 

```
UIViewController *vc1 = [[UIViewController alloc] init];
vc1.tabBarItem = [[UITabBarItem alloc] initWithTitle: @"tab1" image: [UIImage imageNamed: @"tab1"] tag: 0];
    
UIViewController * vc2 = [[UIViewController alloc] init];
vc2.tabBarItem = [[UITabBarItem alloc] initWithTitle: @"tab2" image: [UIImage imageNamed: @"tab2"] tag: 1];

UIViewController * vc3 = [[UIViewController alloc] init];
vc3.tabBarItem = [[UITabBarItem alloc] initWithTitle: @"tab3" image: [UIImage imageNamed: @"tab3"] tag: 2];
    
UIViewController * vc4 = [[UIViewController alloc] init];
vc4.tabBarItem = [[UITabBarItem alloc] initWithTitle: @"tab4" image: [UIImage imageNamed: @"tab4"] tag: 3];
```

 

 

 

 

 

 

 

 

 

 

 

 

 

 

```
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.delegate = self;
self.tabBarController.viewControllers =
[NSArray arrayWithObjects: vc1, vc2, vc3, vc4, nil];
self.tabBarController.tabBar.tintColor = [UIColor greenColor];
self.tabBarController.tabBar.selectedImageTintColor = [UIColor brownColor];
//tabBarController.tabBar.backgroundImage = [UIImage imageNamed:@"@@@@@"];
self.tabBarController.selectedIndex = 1;
```

 

 

 

 

 

 

 

 

 

 

 

 

 

```
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    UIViewController *selectedViewController = tabBarController.selectedViewController;
    if ([viewController isEqual: selectedViewController])
    {
        NSLog(@"AppDelegate#tabBarController:shouldSelectViewController: current selected");
    }
    else
    {
        NSLog(@"AppDelegate#tabBarController:shouldSelectViewController: select");
    }
    return YES;
}
```

添加手势识别

 

添加长按手势识别

\[self.tabBarController.tabBar addGestureRecognizer: longPressRecognizer];

 

```
- (void) longPressGestureRecognized: (UILongPressGestureRecognizer *) recognizer {
    NSLog(@"AppDelegate#longPressGestureRecognized");
    if (self.tabBarController.selectedIndex == 0) // self.tabBarController.tabBar.selectedItem.tag == 0
    {
        NSLog(@"AppDelegate#longPressGestureRecognized: action");
    }
    else
    {
        NSLog(@"AppDelegate#longPressGestureRecognized: no action");
    }
}
```

 

 

 

 

# UITabBarItem

```
UITabBarItem *tab1 = [[UITabBarItem alloc] initWithTitle: nil image: [UIImage imageNamed: @"toolbar_selected_normal"] tag: 0];
    
UITabBarItem * tab2 = [[UITabBarItem alloc] initWithTitle: nil image: [UIImage imageNamed: @"toolbar_default_normal"] tag: 1];
    
UITabBarItem * tab3 = [[UITabBarItem alloc] initWithTitle: nil image: [UIImage imageNamed: @"toolbar_default_normal"] tag: 2];
    
UITabBarItem * tab4 = [[UITabBarItem alloc] initWithTitle: nil image: [UIImage imageNamed: @"toolbar_default_normal"] tag: 3];
    
//NSArray *items = [NSArray arrayWithObjects: tab1, nil];
NSArray *items = @[tab1, tab2, tab3, tab4];
    
[mainTabBar setItems: items];
```

 

 

# UIColor

 

 

# UIImage

 

# 手势识别

 

UIGestureRecognizer

除了默认的init方法，UIGestureRecognizer接口还定义了一个initWithTarget:action:初始化方法。

 

 

\- (instancetype)initWithTarget:(nullableid)target action:(nullableSEL)action NS\_DESIGNATED\_INITIALIZER;

 

如果是采用默认的init方法初始化，可以通过addTarget:action:指定动作执行的方法。

\- (void)addTarget:(id)target action:(SEL)action; 

 

UIGestureRecognizerDelegate

 

# 长按手势识别

UILongPressGestureRecognizer

 

UILongPressGestureRecognizer扩展至UIGestureRecognizer接口。

 

 

UILongPressGestureRecognizer \*longPressRecognizer = \[\[UILongPressGestureRecognizeralloc]    initWithTarget: selfaction: @selector(longPressGestureRecognized:)];

创建一个UILongPressGestureRecognizer对象

 

 

 

 

# 布局

 

# 布局管理

 

# 自动布局

 

# MVC

 

UITabBarController

 

 

# CoreFoundation

 

 

 

# CoreLocation

 

 

CLLocationManager

检查位置服务是否开启

\[CLLocationManager locationServicesEnabled]

 

distanceFilter

表示位置变化多大会有一次定位，它表示一个距离，这是一个过滤器，比如指定为10，表示位置变化移动达到10米就会有一次定位，10米以内的位置变化呗过滤掉。当指定kCLDistanceFilterNone时，表示只要有移动，即只要位置发生变化就会触发定位。

 

kCLDistanceFilterNone

 

CLLocationDistance，其实就是double类型的一个别名。

 

 

desiredAccuracy

表示期望的精度，用于指定一个精确度。位置服务是有一个精度的，精度级别。定位服务将尽力达到您所期望的准确性。然而，虽然这并不能保证。这个是要注意的。

 

desiredAccuracy可以指定以下的一个值。

kCLLocationAccuracyBestForNavigation

 

kCLLocationAccuracyBest

 

kCLLocationAccuracyNearestTenMeters

 

kCLLocationAccuracyHundredMeters

 

kCLLocationAccuracyKilometer

 

kCLLocationAccuracyThreeKilometers

 

 

desiredAccuracy的值是CLLocationAccuracy类型的。其实就是double类型的一个别名。

 

启动触发更新位置

startUpdatingLocation

 

停止触发更新位置

stopUpdatingLocation

 

调用startUpdatingLocation启动触发更新位置，将会触发CLLocationManagerDelegate的locationManager:didUpdateToLocation:fromLocation:方法，这个方法已经废弃，如果实现了locationManager:didUpdateLocations:方法，则触发调用这个方法。如果调用stopUpdatingLocation，则停止触发调用上面的方法。

 

 

```
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
        
//每隔多少米定位一次（这里的设置为任何的移动）
self.locationManager.distanceFilter = kCLDistanceFilterNone;
//设置定位的精准度，一般精准度越高，越耗电（这里设置为精准度最高的，适用于导航应用）
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        
[self.locationManager startUpdatingLocation];
```

 

 

CLLocationManagerDelegate

 

\- (void)locationManager:(CLLocationManager \*)manager

didUpdateToLocation:(CLLocation \*)newLocation

 

  fromLocation:(CLLocation \*)oldLocation \_\_OSX\_AVAILABLE\_BUT\_DEPRECATED(\_\_MAC\_10\_6, \_\_MAC\_NA, \_\_IPHONE\_2\_0, \_\_IPHONE\_6\_0) \_\_TVOS\_PROHIBITED \_\_WATCHOS\_PROHIBITED;

这个方法已经废弃

 

 

\- (void)locationManager:(CLLocationManager \*)manager

 

didUpdateLocations:(NSArray&lt;CLLocation \*&gt; \*)locations \_\_OSX\_AVAILABLE\_STARTING(\_\_MAC\_10\_9,\_\_IPHONE\_6\_0);

 

\- (void)locationManager:(CLLocationManager \*)manager

 

didFailWithError:(NSError \*)error;

 

# Info.plist

 

# 权限

 

位置服务

 

&lt;key&gt;NSLocationAlwaysUsageDescription&lt;/key&gt;

&lt;string&gt;App需要您的同意，才能始终访问位置信息，以便于搜索附近的xxx位置&lt;/string&gt;

&lt;key&gt;NSLocationUsageDescription&lt;/key&gt;

&lt;string&gt;APP需要您的同意，才能访问位置信息，以便于搜索附近的xxx位置&lt;/string&gt;

&lt;key&gt;NSLocationWhenInUseDescription&lt;/key&gt;

&lt;string&gt;APP需要您的同意，才能在使用时获取位置信息，以便于搜索附近的xxx位置&lt;/string&gt;

&lt;key&gt;NSLocationWhenInUseUsageDescription&lt;/key&gt;

 

&lt;string&gt;APP需要您的同意，才能在使用时获取位置信息，以便于搜索附近的xxx位置&lt;/string&gt;

 

MacOS程序导入Foundation或者Cocoa框架导致的一个错误，这个程序之前一直都是运行没问题的，过了一段时间后，再次编译的时候报如下错误：

 

In file included from /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:87:

In file included from /System/Library/Frameworks/Foundation.framework/Headers/NSURLError.h:14:

In file included from /System/Library/Frameworks/CoreServices.framework/Headers/CoreServices.h:23:

In file included from /System/Library/Frameworks/CoreServices.framework/Frameworks/AE.framework/Headers/AE.h:20:

In file included from /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/CarbonCore.h:208:

In file included from /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/HFSVolumes.h:25:

**/usr/include/hfs/hfs\_format.h:794:2: error: unknown type name 'uuid\_string\_t';**

      **did you mean 'io\_string\_t'?**

        uuid\_string\_t   ext\_jnl\_uuid;

        **^**

**/usr/include/device/device\_types.h:89:16: note:** 'io\_string\_t' declared here

typedef char                    io\_string\_t\[512];       

 

                                **^**

In file included from /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:87:

In file included from /System/Library/Frameworks/Foundation.framework/Headers/NSURLError.h:14:

In file included from /System/Library/Frameworks/CoreServices.framework/Headers/CoreServices.h:23:

In file included from /System/Library/Frameworks/CoreServices.framework/Frameworks/AE.framework/Headers/AE.h:20:

In file included from /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/CarbonCore.h:208:

In file included from /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/HFSVolumes.h:25:

**/usr/include/hfs/hfs\_format.h:796:20: error: use of undeclared identifier**

      **'uuid\_string\_t'**

        char            reserved\[JIB\_RESERVED\_SIZE];

                                 **^**

**/usr/include/hfs/hfs\_format.h:787:61: note:** expanded from macro

      'JIB\_RESERVED\_SIZE'

#define JIB\_RESERVED\_SIZE  ((32\*sizeof(u\_int32\_t)) - sizeof(uuid\_string\_t) - 48)

 

                                                            **^**

第1个错误是因为**uuid\_string\_t这个类型没有定义，这个类型在**uuid/uuid.h头文件中定义的，但没有包含uuid/uuid.h头文件，我预编译后看也没有发现包含这个头文件，很奇怪之前都没有这个问题，难道是因为哪里更新的问题，之前并不需要依赖这个头文件，可能是CarbonCore或者这个框架依赖的库更新过，之前不依赖这个头文件，更新了之后又依赖这个头文件了？

 

第2个错误是没有找到JIB\_RESERVED\_SIZE这个定义。这个定义本身是定义了的，但是JIB\_RESERVED\_SIZE的定义又用到了uuid/uuid.h头文件中的uuid\_string\_t。

 

在解决这个问题的时候，uuid\_string\_t在uuid/uuid.h头文件中是如下定义的，\_\_darwin\_uuid\_string\_t这个是在sys/\_types.h头文件中定义的。本来是在程序中直接将uuid/uuid.h、sys/types.h这两个头文件包含进来就可以，sys/types.h头文件包含了sys/\_types.h。

 

typedef \_\_darwin\_uuid\_string\_t uuid\_string\_t;

 

即

#include &lt;sys/types.h&gt;

#include &lt;uuid/uuid.h&gt;

 

但是这样包含之后还是有刚才这个问题。

 

发现这两个文件包含进来后，还是没有找到uuid\_string\_t的定义。

 

然后我直接在程序中自己重新定义这两个类型：

 

typedef char\_\_darwin\_uuid\_string\_t\[37];

typedef \_\_darwin\_uuid\_string\_tuuid\_string\_t;

 

这就解决问题了。

 

最后发现在将上面两个文件包含进来后，sys/types.h文件包含没问题，但uuid/uuid.h头文件包含有问题，在预编译的时候发现，这个头文件包含的是/usr/local/include下面的这个uuid/uuid.h头文件，这里边并没有uuid\_string\_t的定义。而在/usr/include下就有这个uuid/uuid.h头文件，这个下面是有uuid\_string\_t的定义。

 

编译时指定-v查看头文件搜索路径，可以看到先是在/usr/local/include目录下搜索头文件，没有找到后后面才会去/usr/include目录下搜索头文件，这里已经在/usr/local/include目录下找到了uuid/uuid.h这个头文件，那么/usr/include目录下的这个uuid/uuid.h头文件就不会再去找了。

 

\# gcc -framework Cocoa test.m -o test -v

#include "..." search starts here:

#include &lt;...&gt; search starts here:

 /usr/local/include

 /Users/admin/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/include

 /Users/admin/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include

 /usr/include

 /System/Library/Frameworks (framework directory)

 /Library/Frameworks (framework directory)

 

End of search list.

 

最后的原因是我后来自己安装过libuuid这个库。