GVKun编程网logo

LinkedIn API - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started

1

本文将带您了解关于LinkedInAPI-https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/

本文将带您了解关于LinkedIn API - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started的新内容,另外,我们还将为您提供关于1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1...、1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1)npm install -g yarn react-native-cli       安装yarn命令工具和react-native命令工具,Yarn是Facebook提供的替代npm的工具,可以加速n、ArcGIS API for Silverlight开发入门(1):Getting Started、Core Data Tutorial: Getting Started的实用信息。

本文目录一览:

LinkedIn API - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started

LinkedIn API - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started

如何解决LinkedIn API - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started

这里对 LinkedIn Marketing Report API 有点困惑 - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started

本质上,主题是将 URN ID 传递到不同的端点,以接收有关分享/喜欢/广告预算等的不同指标。事情是使用 /me 端点,您只能获得您的帐户 URN ID 和个人 URN ID。没有关于如何找到您的 Share URN ID 或 UCG URN ID 的文档?任何人都有关于如何找到这些信息的好资源?

1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1...

1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1...

http://www.bubuko.com/infodetail-2599307.html

 

1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content

  (1)npm install -g yarn react-native-cli

      安装yarn命令工具和react-native命令工具,Yarn是Facebook提供的替代npm的工具,可以加速node模块的下载。

       React Native的命令行工具用于执行创建、初始化、更新项目、运行打包服务(packager)等任务。 

  (2)yarn config set registry https://registry.npm.taobao.org --global 

     yarn config set disturl https://npm.taobao.org/dist --global

      给yarn工具设置镜像源

 

2.创建react-native项目

  (1)react-native init AwesomeProject

      AwesomeProject 是自定义的项目名,注:进入自己想要的路径上输入此命令,如下图可在app文件夹中创建项目。

      

  (2)cd AwesomeProject

      进入项目文件,在运行之前需要先连接设备。

3.安装模拟器:

  (1)可以下载  夜神模拟器 或者逍遥模拟器, 也可以使用 Genymotion或者Android-studio(这两个就不介绍了)

  (2)连接模拟器:

    夜神模拟器 adb connect 127.0.0.1:62001 
    逍遥模拟器 adb connect 127.0.0.1:21503

    注:当前必须只能有一个机子连着电脑,无论是模拟器还是真机!

  (3)查看是否连接成功

      adb devices

      出现下面的东西就说明手机连接成功,此时就可以启动项目了

      

 

4.开启react-native 项目

    react-native run-android

5.进入项目后会出现红屏:如图

  解决方法:摇一摇手机,模拟器的右边工具栏有摇一摇功能,弹出菜单,选择Dev Settings ---> Debug server host&port for device,在弹出的对话框中输入你电脑的IP:8081,电脑的ip可以在cmd中输入ipconfig 查看, IPv4 地址 . . . . . . . . . . . . : 192.168.2.777(这个)

点击确定,之后reload!

  

 

6. 此时需要重启设备。

  在手机端关闭项目进程,然后在cmd中执行 react-native run-android 重新启动一遍。 此时就大功告成了,可以在项目里面的app.js文件中编译。

 

7.简单补充一下真机的连接调试

  (1)开启开发者模式,设置------》关于手机------》版本号(多点几次)

  (2) 进入开发者选项----》开启usb 调试

  (3)如果你的数据线 连着电脑 输入:adb reverse tcp:8081 tcp:8081

  (4)如果没有使用数据线连接,首先要确保,你的手机要和电脑处在同一个局域网下,然后晃动手机,弹出菜单,选择Dev Settings ---> Debug server       host&port for device,在弹出的对话框中输入你电脑的IP:8081,点击确定,之后reload!

  (5)在真机上运行时可能会遇到白屏的情况,请在设置----》权限管理 开启悬浮窗权

1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1)npm install -g yarn react-native-cli       安装yarn命令工具和react-native命令工具,Yarn是Facebook提供的替代npm的工具,可以加速n

1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1)npm install -g yarn react-native-cli       安装yarn命令工具和react-native命令工具,Yarn是Facebook提供的替代npm的工具,可以加速n

http://www.bubuko.com/infodetail-2599307.html

 

1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content

  (1)npm install -g yarn react-native-cli

      安装yarn命令工具和react-native命令工具,Yarn是Facebook提供的替代npm的工具,可以加速node模块的下载。

       React Native的命令行工具用于执行创建、初始化、更新项目、运行打包服务(packager)等任务。 

  (2)yarn config set registry https://registry.npm.taobao.org --global 

     yarn config set disturl https://npm.taobao.org/dist --global

      给yarn工具设置镜像源

 

2.创建react-native项目

  (1)react-native init AwesomeProject

      AwesomeProject 是自定义的项目名,注:进入自己想要的路径上输入此命令,如下图可在app文件夹中创建项目。

      

  (2)cd AwesomeProject

      进入项目文件,在运行之前需要先连接设备。

3.安装模拟器:

  (1)可以下载  夜神模拟器 或者逍遥模拟器, 也可以使用 Genymotion或者Android-studio(这两个就不介绍了)

  (2)连接模拟器:

    夜神模拟器 adb connect 127.0.0.1:62001 
    逍遥模拟器 adb connect 127.0.0.1:21503

    注:当前必须只能有一个机子连着电脑,无论是模拟器还是真机!

  (3)查看是否连接成功

      adb devices

      出现下面的东西就说明手机连接成功,此时就可以启动项目了

      

 

4.开启react-native 项目

    react-native run-android

5.进入项目后会出现红屏:如图

  解决方法:摇一摇手机,模拟器的右边工具栏有摇一摇功能,弹出菜单,选择Dev Settings ---> Debug server host&port for device,在弹出的对话框中输入你电脑的IP:8081,电脑的ip可以在cmd中输入ipconfig 查看, IPv4 地址 . . . . . . . . . . . . : 192.168.2.777(这个)

点击确定,之后reload!

  

 

6. 此时需要重启设备。

  在手机端关闭项目进程,然后在cmd中执行 react-native run-android 重新启动一遍。 此时就大功告成了,可以在项目里面的app.js文件中编译。

 

7.简单补充一下真机的连接调试

  (1)开启开发者模式,设置------》关于手机------》版本号(多点几次)

  (2) 进入开发者选项----》开启usb 调试

  (3)如果你的数据线 连着电脑 输入:adb reverse tcp:8081 tcp:8081

  (4)如果没有使用数据线连接,首先要确保,你的手机要和电脑处在同一个局域网下,然后晃动手机,弹出菜单,选择Dev Settings ---> Debug server       host&port for device,在弹出的对话框中输入你电脑的IP:8081,点击确定,之后reload!

  (5)在真机上运行时可能会遇到白屏的情况,请在设置----》权限管理 开启悬浮窗权

ArcGIS API for Silverlight开发入门(1):Getting Started

ArcGIS API for Silverlight开发入门(1):Getting Started

 这一节来对Silverlight API(ArcGIS API for Silverlight,下同)的开发有个总体的认识。

        欲善其事先利其器。要做开发,第一步就得搭建环境。因为是在Siverlight基础上做开发,所以先得整理好Siverlight的开发环境。Silverlight并没在VS2008中,而是作为add-on的形式附加的。在

可以找到详细的安装步骤:

 说明一下,步骤1安装了Silverlight add-on(要求有IDE的SP1补丁包);步骤2安装的是ExpressionStudio中的ExpressionBlend,这个工具相当于可视化的xaml编辑器,可以用来轻松的创建Silverlight程序的用户界面;步骤3中安装的是Silverlight一种非常华丽的图片处理效果,可以参看这里的实例;步骤4包括一些可用的Silverlight控件和例子。接下来再去看看Silverlight API的要求。可以看出对于开发ArcGIS Silverlight程序来说,只有步骤1是必须的,其他都是可选的。之后需要从ESRI网站下载Silverlight API(需要免费注册一个ESRI Global账户),以备后用。
        总结一下最常见的安装步骤:1、安装VS2008;2、安装
VS2008 SP1;3、安装Silverlight Tools for Visual Studio 2008 SP1。到此,就可进行Silverlight程序的开发了。关于开发环境的搭建,还可以参考yyilyzbc版主的帖子。(做Silverlight API的开发不需要在自己的机器上安装ArcGIS Server,可直接使用ArcGIS Online上的数据;但如果要添加自己的数据,当然还是需要ArcGIS Server了)
        下面就来一个Hello World吧,对于GIS来说,理所当然就是展示一张漂亮的世界地图了。具体步骤如下:
1、VS2008中,新建project,选择Silverlight Application;
2、在出现的提示框中选择Add a new ASP.NET Web project to the solution to hostSilverlight;(Silverlight程序与flash一样,相当于网页中的一个插件。第一个选项是将Silverlight嵌入到一个ASP.NET网站中,第二个选项是将Silverlight嵌入到一个临时的html页面中)
3、添加Silverlight API的引用:与.NET程序开发一样,add reference(注意是在Silverlight工程上而不是ASP.NET工程上),找到从ESRI下载的API,选择添加ESRI.ArcGIS.dll;
4、打开Page.xaml,在UserControl标签中添加一句引用,在Grid标签之间添加一些代码,完成后看起来像这样:

  1. <UserControl x:
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:esri="clr-namespace:ESRI.ArcGIS;assembly=ESRI.ArcGIS"
  5. Width="400" Height="300">
  6. <Grid x:Name="LayoutRoot" Background="White">
  7. <esri:Map x:Name="mymap">
  8.    <esri:Map.Layers>
  9.        <esri:ArcGISTiledMapServiceLayer ID="layerworldmap"
  10.       Url="http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer" />
  11.    </esri:Map.Layers>
  12. </esri:Map>
  13. </Grid>
  14. </UserControl>
复制代码
5、按F5,运行程序,就完成了我们的hello world in
GIS可以在浏览器中看到下面的画面:


看到效果之后,再来对它进行理解吧。
        先说下Silverlight的程序的基本背景。page.xaml实际上是一个控件,相当于asp.net中的default.aspx,大部分的工作都在这里面完成(app.xaml相当于global.asax);上面的是xaml(读:[ig`zeml])代码,是微软针对wpf/silverlight的标记语言,与flex中的mxml类似。Silverlight程序中所有的布局工作都是由xaml来完成的;Silverlight2中,VS2008可以实时对xaml的效果做预览,但是这个预览效果是只读的,对于预览中的控件也不可选;为了弥补这个缺陷,可以用前面提到的ExpressionBlend来可视化地设计程序界面,会自动生成对应的xaml代码,使用于复杂的布局和美化工作(可参考Silverlight中的clock例子);再看page.xaml。usercontrol标签(页面的根元素)证明了page.xaml实际上是一个控件类;下面的几句相当于引入了xml的特定命名空间,里面包括了我们的ESRI.ArcGIS;width和height指明了Silverlight控件本身的尺寸,一般我们将这里的width和height属性去掉,已达到全屏的效果(你也可以试试哦);Grid标签是布局控件,相当于html中的表格,可以进行灵活的页面布局,xaml中常用的布局控件还有Canvas和StackPanel;每一个xaml的Control都可以有一个x:Name属性,以便在code-behind页面中对其引用。
        之后是我们的主角了。Map标签(继承自xaml的Control)相当于一个Map控件,可以在其中加入图层;这里我们添加了一个ArcGISTiledMapServiceLayer图层(在后面的文章中会专门讲到SilverlightAPI中的图层类型),对应使用的是ArcGIS Server发布的经过cache的服务,作为客户端的API,同JavaScript与FlexAPI一样,都是通过REST方式对资源和操作进行引用的;对这个图层,赋予了一个ID属性,因为SilverlightAPI中的图层是从xaml中的DependencyObject继承而来,所以没有x:Name的属性,为了方便在code-behind(与asp.net类似的托管代码)的代码中找到这个图层,便使用了ID属性;URL的内容便是ArcGIS Online发布好的一个世界地图资源。
        到此,应该对这个例子理解的差不多了。如果还想再添加一个图层怎么办呢?没错,就是在Map标签中再添加一个layer,不过要注意的是,第一个加入的图层会显示在最下面,并且决定了整个Map控件的空间参考信息。
        大家自然会想到叠加一个自己的数据图层来看看效果,于是对Map标签内容做了修改(china是本机发布的一个中国地图):

  1. <esri:ArcGISDynamicMapServiceLayer ID="chinamaplayer"
  2.           Url="http://localhost/ArcGIS/rest/services/china/MapServer" />
复制代码
运行后却还是只有世界地图一个图层(已经确保拼写、大小写正确),怎么回事呢?来用事件帮助查找错误吧。
        Silverlight能够利用.net的一些核心库内容,包括事件。来对刚才的那个图层添加一个事件:InitializationFailed,当图层添加失败的时候会出发这个事件。添加这个事件的处理也非常简单:在上面的图层中加入InitializationFailed属性,会提示你生成新的eventhandler,默认回车,看上去像这样:
  1. <esri:ArcGISDynamicMapServiceLayerID="chinamaplayer"InitializationFailed="ArcGISDynamicMapServiceLayer_InitializationFailed"
  2.           Url="http://localhost/ArcGIS/rest/services/china/MapServer" />
复制代码
在事件上面右键单击,Navigate to Event Handler,就会进入前面所说的code-behind页面(本例为C#),添加以下代码:
  1. private void ArcGISDynamicMapServiceLayer_InitializationFailed(object sender,EventArgs e)
  2.       {
  3.           ESRI.ArcGIS.Layer layer = sender as ESRI.ArcGIS.Layer;
  4.           MessageBox.Show(layer.InitializationFailure.Message);
  5.       }
复制代码
然后运行程序,会得到初始化图层失败的原因:


原来,为了安全原因考虑,同flash一样,Silverlight对跨域访问也做了严格的限制。要解决这个问题,可以参考帮助中的说明,将两个xml文件保存在网站根目录,比如C:\Inetpub\wwwroot中即可(其实保存其中一个就可以了,ArcGISOnline已经将两个xml文件都放在了网站根目录中,所以我们可以引用上面的服务)。
        看下最后的效果吧。


 为了更好的理解xaml和Silverlight,建议首先独立完成Silverlight帮助中的两个workthrough:hello worldclock

Core Data Tutorial: Getting Started

Core Data Tutorial: Getting Started

Note from Ray: This is an abbreviated version of a chapter from Core Data by Tutorials released as part of the iOS 8 Feast to give you a sneak peek of what’s inside the book. We hope you enjoy!

In this tutorial, you’ll write your very first Core Data app using Swift. You’ll see how easy it is to get started with all the resources provided in Xcode, from the starter code templates to the data model editor. By the end of the tutorial you’ll know how to:

  • model data you want to store in Core Data using Xcode’s model editor;
  • add new records to Core Data;
  • fetch a set of records from Core Data;
  • display the fetched results to the user in a table view.

You’ll also get a sense of what Core Data is doing behind the scenes, and how you can interact with the various moving pieces there. We’re getting ahead of ourselves though – it’s time to build an app!

Getting Started

Open Xcode and create a new iPhone project based on the Single View Application template. Call the appHitList and make sure Use Core Data is checked:

Checking the Use Core Data box will cause Xcode to generate boilerplate code for what’s known as a Core Data stack in AppDelegate.swift.

The Core Data stack consists of a set of objects that facilitate saving and retrieving information from Core Data. There’s an object to manage the Core Data state as a whole, an object representing the data model, and so on.

Note: Not all Xcode templates have the option to start with Core Data. In Xcode 6, only the Master-Detail Application and the Single View Application templates have the Use Core Data checkbox.

The idea for this sample app is simple. There will be a table view with a list of names for your very own “hit list”. You’ll be able to add names to this list and eventually, you’ll use Core Data to make sure the data is stored between sessions. We don’t condone violence in this tutorial so you can think of this app as a “favorites list” to keep track of your friends too, of course! ;]

Click on Main.storyboard to open it in Interface Builder. Select its only view controller and change its size class to Regular Height and Compact Width to match an iPhone in portrait mode:

Next, embed the view controller in a navigation controller. From Xcode’s Editor menu, select Embed In…\ Navigation Controller.

Back in Interface Builder, drag a Table View from the object library into the view controller so that it covers the entire view.

Then, drag a Bar Button Item and place it on the view controller’s newly added navigation bar. Finally, double-click the bar button item to change its text to Add. Your canvas should now look like the following screenshot:

Every time you tap Add on the top-right, an alert containing a text field will appear on the screen. From there you’ll be able to type someone’s name into the text field. Dismissing the alert will save the name and refresh the table view with all the names you’ve saved up to that point.

Before you can do that, you need to make the view controller the table view’s data source. Ctrl-drag from the table view to the yellow view controller icon above the navigation bar, as shown below, and click on dataSource:

In case you were wondering, you don’t need to set up the table view’s delegate since tapping on the cells won’t trigger any action. It doesn’t get simpler than this!

Open the Assistant Editor by hitting Command-Option-Enter or by selecting the middle button on the Editor toolset on the Xcode bar. Ctrl-drag from the table view onto ViewController.swift, inside the class definition to insert an outlet:

Name the new IBOutlet property tableView, resulting in the following line:

@IBOutlet weak var tableView: UITableView!

Ctrl-drag from the Add bar button item onto ViewController.swift, but this time, create an action instead of an outlet and name the method addName:

@IBAction func addName(sender: AnyObject) {}

You can now refer to the table view and the bar button item’s action in code. Next, set up the model for the table view. Add the following property to ViewController.swift:

//Insert below the tableView IBOutletvar names = [String]()

names is a mutable Array to hold the strings for the table view to display.

Replace the implementation of viewDidLoad with the following:

override func viewDidLoad() {super.viewDidLoad()
  title = "\"The List\""
  tableView.registerClass(UITableViewCell.self,
    forCellReuseIdentifier: "Cell")}

This will set a title and register the UITableViewCell class with the table view. You do this so that when you dequeue a cell, the table view will return a cell of the correct type.

Still in ViewController.swift, declare that ViewController will conform to the UITableViewDataSource protocol by editing the class declaration:

//Add UITableViewDataSource to class declarationclass ViewController: UIViewController, UITableViewDataSource {

Immediately, Xcode will complain about ViewController not conforming to the protocol.

Below viewDidLoad, implement the following data source methods to fix the error:

// MARK: UITableViewDataSourcefunc tableView(tableView: UITableView,
    numberOfRowsInSection section: Int) -> Int {return names.count}func tableView(tableView: UITableView,
  cellForRowAtIndexPath
  indexPath: NSIndexPath) -> UITableViewCell {let cell =
        tableView.dequeueReusableCellWithIdentifier("Cell")as! UITableViewCell
 
    cell.textLabel!.text = names[indexPath.row]return cell
}

If you’ve ever worked with UITableView, this code should look very familiar. The first method says that the table view will have as many rows as the names array has strings.

The second method, tableView(_:cellForRowAtIndexPath:), dequeues table view cells and populates them with the corresponding string in the names array.

Don’t run the app just yet. First, you need a way to input names so the table view can display them.

Implement the addName IBAction method you Ctrl-dragged into your code earlier:

//Implement the addName IBAction
@IBAction func addName(sender: AnyObject) {var alert = UIAlertController(title: "New name",
      message: "Add a new name",
      preferredStyle: .Alert)let saveAction = UIAlertAction(title: "Save",
   style: .Default) { (action: UIAlertAction!) -> Void inlet textField = alert.textFields![0] as! UITextFieldself.names.append(textField.text)self.tableView.reloadData()}let cancelAction = UIAlertAction(title: "Cancel",
    style: .Default) { (action: UIAlertAction!) -> Void in}
 
  alert.addTextFieldWithConfigurationHandler {(textField: UITextField!) -> Void in}
 
  alert.addAction(saveAction)
  alert.addAction(cancelAction)
 
  presentViewController(alert,
      animated: true,
      completion: nil)}

Every time you tap the Add bar button item, this method presents an UIAlertController with a text field and two buttons, Save and Cancel.

Save takes whatever text is currently in the text field, inserts it into the name array and reloads the table view. Since the names array is the model backing the table view, whatever you typed into the text field will appear in the table view.

Finally it’s time to build and run your app for the first time. Tap the Add bar button item. The alert controller will look like this:

Add four or five names to the list. You should wind up with something like this:

Your table view will display the data and your array will store the names, but the big thing missing here ispersistence. The array is in memory but if you force quit the app or reboot your device, your hit list will be wiped out.

Core Data provides persistence, meaning it can store data in a more durable state so that it can outlive an app re-launch or a device reboot.

You haven’t added any Core Data yet, so nothing should persist after you navigate away from the app. Let’s test this out. Press the Home button if you’re using a physical device or the equivalent (Shift+⌘+H) if you’re on the Simulator. This will take you back to the familiar app grid on the home screen:

From the home screen, tap the HitList icon to bring the app back to the foreground. The names are still on the screen. What happened?

When you tap the Home button, the app that’s currently in the foreground goes to the background. When this happens, the operating system flash-freezes everything currently in memory, including the strings in the namesarray. Similarly, when it’s time to wake up and return to the foreground, the operating system restores what used to be in memory as if you’d never left.

Apple introduced these advances in multitasking back in iOS 4. They create a seamless experience for iOS users but add a wrinkle to the definition of persistence for iOS developers. Are the names really persisted?

No, not really. If you had completely killed the app in the fast app switcher or turned off your phone, those names would be gone. You can verify this, as well. With the app in the foreground, double tap the Home button to enter the fast app switcher, like so:

From here, flick the HitList app snapshot upwards to terminate the app. There should be no trace of HitList in living memory (no pun intended). Verify that the names are gone by returning to the home screen and tapping on the HitList icon to trigger a fresh launch.

This difference between flash-freezing and persistence may be obvious if you’ve been working with iOS for some time and are familiar with the way multitasking works. In a user’s mind, however, there is no difference. The user doesn’t care if the names are “still there” because the app went into the background and came back, or because the app saved and reloaded them.

All that matters is that the names are still there when she comes back!

So the real test of persistence, the one you will use in this tutorial, is whether your data is still there after a fresh app launch.

Modeling Your Data

Now that you know how to check for persistence, let’s get started with Core Data. Your goal for the HitList app is simple: to persist the names you enter so they’re available for viewing after a fresh app launch.

Up to this point, you’ve been using plain old Swift strings to store the names in memory. In this section, you’ll replace these strings with Core Data objects.

The first step is to create a managed object model, which spells out the way Core Data represents data on disk. By default, Core Data uses an SQLite database as the persistent store (more on this later), so you can think of the data model as the database schema.

Note: You’ll come across the word “managed” quite a bit in this tutorial. If you see “managed” in the name of a class, such as in NSManagedObjectContext, chances are you are dealing with a Core Data class. “Managed” refers to Core Data’s management of the life cycle of Core Data objects.

However, don’t assume that all Core Data classes contain the word “managed”—actually, most don’t. For a comprehensive list of Core Data classes, check out the Objective-C umbrella header CoreData/CoreData.h.

Since you elected to use Core Data when you created the HitList project, Xcode automatically created a data model file for you and named it HitList.xcdatamodeld.

Click on HitList.xcdatamodeld to open it. As you can see, Xcode has a powerful data model editor that looks like this:

The data model editor has a lot of features. For now, let’s focus on creating a single Core Data entity.

Click on Add Entity on the lower-left to create a new entity. Double-click on the new entity and change its name to Person, like so:

You may be wondering why the model editor uses the term “Entity.” Weren’t you simply defining a new class? As you’ll see shortly, Core Data comes with its own vocabulary. Here’s a quick rundown of some of the terms you’ll commonly encounter:

  • An entity is a class definition in Core Data. The classic example is an Employee or a Company. In a relational database, an entity corresponds to a table.
  • An attribute is a piece of information attached to a particular entity. For example, an Employee entity could have attributes for the employee’s name, position and salary. In a database, an attribute corresponds to a particular field in a table.
  • relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships. For example, a Manager can have a to-many relationship with a set of employees, whereas an individualEmployee will have a to-one relationship with his manager.

Note: As you’ve probably noticed, entities sound a lot like a classes. Likewise, attributes/relationships sound a lot like properties. What’s the difference? You can think of a Core Data entity as a class “definition” and the managed object as an instance of that class.

Now that you know what an attribute is, go back to the model editor and add an attribute to Person. SelectPerson on the left-hand side and click the plus sign (+) under Attributes.

Set the new attribute’s name to, well, name and change its type to String:

In Core Data, an attribute can be of one of several data types — one of them is the string type.

Saving to Core Data

Import the Core Data module at the top of ViewController.swift:

//Add below "import UIKit"import CoreData

You may have had to link frameworks manually in your project’s Build Phases if you’ve worked with Objective-C frameworks. In Swift, a simple import statement is all you need to start using Core Data APIs in your code.

Next, replace the table view’s model with the following:

//Change [String] to [NSManagedObject]var people = [NSManagedObject]()

You’ll be storing Person entities rather than just names, so you rename the Array that serves as the table view’s data model to people. It now holds instances of NSManagedObject rather than simple Swift strings.

NSManagedObject represents a single object stored in Core Data—you must use it to create, edit, save and delete from your Core Data persistent store. As you’ll see shortly, NSManagedObject is a shape-shifter. It can take the form of any entity in your data model, appropriating whatever attributes and relationships you defined.

Since you’re changing the table view’s model, you must also replace both data source methods you implemented earlier with the following to reflect these changes:

//Replace both UITableViewDataSource methodsfunc tableView(tableView: UITableView,
    numberOfRowsInSection section: Int) -> Int {return people.count}func tableView(tableView: UITableView,
  cellForRowAtIndexPath
  indexPath: NSIndexPath) -> UITableViewCell {let cell =
    tableView.dequeueReusableCellWithIdentifier("Cell")as! UITableViewCelllet person = people[indexPath.row]
    cell.textLabel!.text = person.valueForKey("name") as? Stringreturn cell
}

The most significant change to these methods occurs in cellForRowAtIndexPath. Instead of matching cells with the corresponding string in the model array, you now match cells with the corresponding NSManagedObject.

Note how you grab the name attribute from the NSManagedObject. It happens here:

cell.textLabel!.text = person.valueForKey("name") as? String

Why do you have to do this? As it turns out, NSManagedObject doesn’t know about the name attribute you defined in your data model, so there’s no way of accessing it directly with a property. The only way Core Data provides to read the value is key-value coding, commonly referred to as KVC.

Note: If you’re new to iOS development, you may not be familiar with key-value coding or KVC.

KVC is a mechanism in Cocoa and Cocoa Touch for accessing an object’s properties indirectly using strings to identify properties. In this case, KVC makes NSMangedObject behave more or less like a dictionary.

Key-value coding is available to all classes that descend from NSObject, including NSManagedObject. You wouldn’t be able to access properties using KVC on a Swift object that doesn’t descend from NSObject.

Next, replace the save action in the addName @IBAction method with the following:

let saveAction = UIAlertAction(title: "Save",
 style: .Default) { (action: UIAlertAction!) -> Void inlet textField = alert.textFields![0] as! UITextFieldself.saveName(textField.text)self.tableView.reloadData()}

This takes the text in the text field and passes it over to a new method called saveName. Add saveName toViewController.swift, as shown below:

func saveName(name: String) {//1let appDelegate =UIApplication.sharedApplication().delegate as! AppDelegate
 
  let managedContext = appDelegate.managedObjectContext!//2let entity =  NSEntityDescription.entityForName("Person",
    inManagedObjectContext:
    managedContext)let person = NSManagedObject(entity: entity!,
    insertIntoManagedObjectContext:managedContext)//3
  person.setValue(name, forKey: "name")//4var error: NSError?
  if !managedContext.save(&error) {println("Could not save \(error), \(error?.userInfo)")}//5
  people.append(person)}

This is where Core Data kicks in! Here’s what the code does:

  1. Before you can save or retrieve anything from your Core Data store, you first need to get your hands on anNSManagedObjectContext. You can think of a managed object context as an in-memory “scratchpad” for working with managed objects.

    Think of saving a new managed object to Core Data as a two-step process: first, you insert a new managed object into a managed object context; then, after you’re happy with your shiny new managed object, you “commit” the changes in your managed object context to save it to disk.

    Xcode has already generated a managed object context as part of the new project’s template – remember, this only happens if you check the Use Core Data checkbox at the beginning. This default managed object context lives as a property of the application delegate. To access it, you first get a reference to the app delegate.

  2. You create a new managed object and insert it into the managed object context. You can do this in one step with NSManagedObject’s designated initializer: init(entity:insertIntoManagedObjectContext:).

    You may be wondering what an NSEntityDescription is all about. Recall that earlier, I calledNSManagedObject a “shape-shifter” class because it can represent any entity. An entity description is the piece that links the entity definition from your data model with an instance of NSManagedObject at runtime.

  3. With an NSManagedObject in hand, you set the name attribute using key-value coding. You have to spell the KVC key (“name” in this case) exactly as it appears on your data model, otherwise your app will crash at runtime.
  4. You commit your changes to person and save to disk by calling save on the managed object context. Note that save takes one parameter, which is a pointer to an NSError; if there is ever an error with the save operation, you can inspect the error and alert the user if necessary.
  5. Congratulations! Your new managed object is now safely ensconced in your Core Data persistent store. Insert the new managed object into the people array so that it shows up in the table view when it reloads.

That’s a little more complicated than an array of strings, but not too bad. Some of the code here—getting the managed object context and entity¬—could be done just once in your own init or viewDidLoad and then reused later. For simplicity, you’re doing it all at once in one method.

Build and run the app, and add a few names to the table view:

Note: If your application crashed when you tried to add the first name, make sure you renamed your Core Data entity from Entity to Person in HitList.xcdatamodeld. If this happened to you, delete the app and re-build from scratch after you change it to Person.

If the names are actually stored in Core Data, the HitList app should pass the persistence test. Double-tap the Home button to bring up the fast app switcher. Terminate the HitList app by flicking it upwards.

From Springboard, tap the HitList app to trigger a fresh launch. Wait, what happened? The table view is empty:

You saved to Core Data, but after a fresh app launch, the people array is empty! The data is actually sitting there waiting, but you haven’t fetched it yet.

Fetching from Core Data

To get data from your persistent store and into the managed object context, you have to fetch it. Add the following method to ViewController.swift:

override func viewWillAppear(animated: Bool) {super.viewWillAppear(animated)//1let appDelegate =UIApplication.sharedApplication().delegate as! AppDelegate
 
  let managedContext = appDelegate.managedObjectContext!//2let fetchRequest = NSFetchRequest(entityName:"Person")//3var error: NSError?
 
  let fetchedResults =
    managedContext.executeFetchRequest(fetchRequest,
    error: &error) as? [NSManagedObject]if let results = fetchedResults {
    people = results
  } else {println("Could not fetch \(error), \(error!.userInfo)")}}

Step by step, this is what the code does:

  1. As mentioned in the previous section, before you can do anything with Core Data, you need a managed object context. Fetching is no different! You pull up the application delegate and grab a reference to its managed object context.
  2. As the name suggests, NSFetchRequest is the class responsible for fetching from Core Data. Fetch requests are both powerful and flexible. You can use requests to fetch a set of objects that meet particular criteria (e.g., “give me all employees that live in Wisconsin and have been with the company at least three years”), individual values (e.g., “give me the longest name in the database”) and more.

    Fetch requests have several qualifiers that refine the set of results they return. For now, you should know that NSEntityDescription is one of these qualifiers (one that is required!).

    Setting a fetch request’s entity property, or alternatively initializing it with init(entityName:), fetches all objects of a particular entity. This is what you do here to fetch all Person entities.

  3. You hand the fetch request over to the managed object context to do the heavy lifting.
    executeFetchRequest(_:error:) returns an optional array of managed objects that meets the criteria specified by the fetch request.

Note: If there are no objects that match the fetch request’s criteria, the method returns an optional value containing an empty array.

If an error occurred during the fetch, the method returns an optional value that contains nil. If this happens, you can inspect the NSError and respond appropriately.

Build and run the application once again. Immediately, you should see the list of names you added earlier:

Great! They’re back from the dead. Add a few more names to the list and restart the app to verify that saving and fetching are working properly. Short of deleting the app, resetting the Simulator or throwing your phone off a tall building, the names will appear in the table view no matter what.

Where To Go From Here?

In this tutorial you experienced several fundamental Core Data concepts: data models, entities, attributes, managed objects, managed object contexts and fetch requests. Here is the completed HitList project, fully integrated with Core Data.

There were a few rough edges in the HitList app: you had to get the managed object context from the app delegate each time, and you used KVC to access the attributes rather than a more natural object-style person.name. As you can see, Core Data is a large and extensive topic. There’s a lot more to learn!

If you’d like to learn more about creating Core Data applications using Swift, check out our book Core Data by Tutorials where you can go deeper into more advanced Core Data topics such as iCloud/Core Data integration, versioning and migration.

If you have any questions or comments on this tutorial, please join the forum discussion below!


来源: <http://www.raywenderlich.com/85578/first-core-data-app-using-swift>
 

来自为知笔记(Wiz)


我们今天的关于LinkedIn API - https://docs.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/getting-started的分享就到这里,谢谢您的阅读,如果想了解更多关于1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1...、1.在cmd界面搭建react-native 环境: 可参考https://reactnative.cn/docs/0.51/getting-started.html#content   (1)npm install -g yarn react-native-cli       安装yarn命令工具和react-native命令工具,Yarn是Facebook提供的替代npm的工具,可以加速n、ArcGIS API for Silverlight开发入门(1):Getting Started、Core Data Tutorial: Getting Started的相关信息,可以在本站进行搜索。

本文标签: